fstream - read word to file c++ -
i want user word , put place in file certian word. have problem getline. in new file don't have new line. when add newline string write file, line read 2 times , writeto file times (i think bcoz saw newfile)
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string contain_of_file,bufor,word,empty=" ",new_line="\n"; string conection; string::size_type position; cout<<"give word"; cin>>word; ifstream newfile; ofstream nowy1; nowy1.open("tekstpa.txt", ios::app); newfile.open("plik1.txt"); while(newfile.good()) { getline(newfile, contain_of_file); cout<<contain_of_file; position=contain_of_file.find("zuzia"); if(position!=string::npos) { conection=contain_of_file+empty+word+new_line; nowy1<<conection; } nowy1<<contain_of_file; } nowy1.close(); newfile.close(); cin.get(); return 0; }
the problem here not reading. directly, loop.
do not loop while (stream.good())
or while (!stream.eof())
. because eofbit
flag not set until after try read beyond file. means loop iterate 1 time, , try read file std::getline
call fails don't notice , continue if nothing happened.
instead do
while (std::getline(newfile, contain_of_file)) { ... }
and unrelated tip: variable conection
not needed, can instead just
nowy1 << contain_of_file << ' ' << word << '\n';
Comments
Post a Comment