简体   繁体   中英

read word to file c++

I want get from user word and put into place in file where is certian word. I have problem with getline. In new file I don't have any new line. When I add Newline to string which I write to file, this line is read two times and writeto file to times (I think that bcoz I saw this 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 a 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 is not your reading. directly, but about your loop .

Do not loop while (stream.good()) or while (!stream.eof()) . This is because the eofbit flag is not set until after you try to read from beyond the file. This means that the loop will iterate one extra time, and you try to read from the file but the std::getline call will fails but you don't notice it and just continue as if nothing happened.

Instead do

while (std::getline(NewFile, contain_of_file)) { ... }

And an unrelated tip: The variable conection is not needed, you can instead do just

Nowy1 << contain_of_file << ' ' << word << '\n';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM