簡體   English   中英

讀單詞到文件c ++

[英]read word to file c++

我想從用戶單詞中獲取並放置在文檔單詞是地方單詞的地方。 我對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';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM