我想从用户词中获取并放入 certian 词所在的文件中。 我对 getline 有疑问。 在新文件中我没有任何新行。 当我将换行符添加到我写入文件的字符串时,该行被读取两次并写入文件多次(我认为 bcoz 我看到了这个新文件)
#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;
}
最佳答案
这里的问题不是你的阅读。直接,但关于你的循环。
不要循环 while (stream.good())
或 while (!stream.eof())
。这是因为 eofbit
标志在您尝试读取文件之外的内容之前之后 不会设置。这意味着循环将重复一次额外的时间,并且您尝试从文件中读取,但 std::getline
调用将失败,但您没有注意到它并且只是继续,就好像什么也没发生一样。
改为做
while (std::getline(NewFile, contain_of_file)) { ... }
还有一个不相关的提示:不需要变量 conection
,您可以直接这样做
Nowy1 << contain_of_file << ' ' << word << '\n';
关于c++ - 读取单词到文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893363/