c++ - File not displaying on cmd prompt window -
i new c++. takking class on intro structures , objects right now. finnaly went on files , got idea write program encrypts text file. own pleasure , knowledge (this not homework). havent written encryption yet, private key because told easiest , first time trying this. anyway writing code functions right make sure work, make them classes later on , expand on program. so, right code open , write file. want view file wrote in cmd window before encrypting know can see before , after. heres code:
//this program create, store , encrypt file sending on inernet #include<iostream> #include<cstdlib> #include<iomanip> #include<string> #include<fstream> #include"fileselect.h" using namespace std; void openfile(fstream &); void readfile(fstream &); int main() { //output file stream fstream outputstream; fstream inputstream; string filename, line; openfile(outputstream); readfile(inputstream); system("pause"); return 0; } //open file def void openfile(fstream &fout){ string filename; char ch; cout<<"enter name of file open: "; getline(cin, filename); //try open file writing fout.open(filename.c_str(),ios::out); if(fout.fail()){ cout<<"file, "<<filename<<" failed open.\n"; exit(1); } cout<<"enter message encrypt. end message '&':\n"; cin.get(ch); while(ch!='.'){ fout.put(ch); cin.get(ch); } fout.close(); return; } void readfile(fstream &fin){ string filename, line; cout<<endl; cout<<"enter name of file open: "; getline(cin, filename); //check file if(fin.fail()){ cout<<"file "<<filename<<" failed open.\n"; exit(1); } cout<<"opening "<<"'"<<filename<<"'" <<endl; //cout<<"enter file open: "; //cin>>filename; fin.open(filename.c_str(),ios::in); //readfile(inputstream); if(fin){ //read in data getline(fin,line); while(fin){ cout<<line<<endl; getline(fin,line); } fin.close(); } else{ cout<<"error displaying file.\n"; } return ; } this compile , run. if openfile() commented out , readfile() function called itself, file read written in openfile(). wont 1 after other want. simple fix missing becoming bit of headache now. apreciated. thank you.
when read message encrypt, don't consume newline. newline remains in input buffer , cause getline(cin, filename); read empty filename.
you must first skip newline after reading message
string tmp; getline(cin, tmp); and getline() in readfile work properly.
ot:
your prompt says
cout<<"enter message encrypt. end message '&':\n";but test
., not&while(ch!='.'){you pass
fstreambothopenfile,readfile, open , close files in these functions. can use local variable instead.instead of
void openfile(fstream &fout){ ... fout.open(filename.c_str(),ios::out);you write
void openfile(){ ... fstream fout; fout.open(filename.c_str(),ios::out);or shorter
void openfile(){ ... ofstream fout(filename.c_str());additionally, must change declaration , call of
openfile().readfile,fin/ifstreamwork appropriately.
Comments
Post a Comment