c++ - 读取单词到文件 C++

标签 c++ fstream

我想从用户词中获取并放入 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/

相关文章:

Java vs C++ (g++) vs C++ (Visual Studio) 性能

c++ - 模板扣: why it works with inheritance (when it fails with conversion)?

c++ - 如何逐行读取一个文件到一个字符串类型的变量?

C++ ifstream 对象 "reseting"

c++ - 如何存储以二进制模式 C++ 读取的文件中的数据

c++ - MinGW C++ : Reading a file with non-ascii file name

c++ - Boost.ASIO 性能不佳

c++ - 间接 Typelib 未从 Debug dll 中很好地导入

c++ - C++ 函数中的复杂参数 - 指针、引用或...?

c++ - 如何从 C++ 程序中打开进程并将结果读入 ifstream?