【问题标题】:getline dosnt read or return from filegetline 不从文件读取或返回
【发布时间】:2015-07-24 01:31:40
【问题描述】:

我正在尝试从文件中读取一个字符串并将其与另一个字符串进行比较。 由于某种原因,getline 只是返回并空行。

int count =0;
string line;
ifstream emailFile;
emailFile.open("email.txt");


if (emailFile.is_open())
{
    cout << "file open \n";


while (emailFile.eof()!=true)
{
    getline(emailFile,line);
    cout <<line<<endl;


        for (int i=0; i<27; i++)
        {
            cout <<"line: "<< line << endl;
            cout<< "Spamword: "<< spamWords[i]<<endl;
            if (line.find(spamWords[i]) != string::npos)
            {
                cout <<"found line: "<< line << endl;
                cout<< "found Spamword: "<< spamWords[i]<<endl;
                count +=2;
            }

        }
}
}

else cout<< "file not found";

cout <<count;

}

我已尝试对其进行故障排除,但我真的不明白为什么没有读取任何内容。

任何帮助将不胜感激。

【问题讨论】:

  • 不要丢弃getline的返回值。
  • @KerrekSB 是的。 obsi,将while (!eof) 行更改为while (getline(emailFile, line)) 这将捕获您可能关心的所有错误情况。也读一读:stackoverflow.com/questions/5605125/…

标签: c++ text-files fstream getline


【解决方案1】:

这个人遇到了和你一样的问题。

http://www.cplusplus.com/forum/beginner/27799/

确保您的 txt 文件位于 exe 内置的同一目录中。 从上面的链接中,这行代码可能有助于确保您确实在文件中。

//Check if data file is open and reports
if(read.is_open())
  cout << "File ./" << file_name << " is open.\n";
  else
cout << "Error opening " << file_name << ".\n";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2018-11-01
    • 1970-01-01
    • 2021-06-27
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多