简体   繁体   English

C ++ FileReader提供错误

[英]C++ filereader giving error

I got code for a filereader for C++ from a website but I can't seem to get it to work for me, is there something wrong with the code or should I just use something else to read text form a textfile? 我从网站上获得了用于C ++的FileReader的代码,但似乎无法为我工作,代码有什么问题吗?还是我应该使用其他东西来读取文本文件中的文本?

The Error I get is: 我得到的错误是:

E:\\IT-C++\\snake.cpp||In function 'int main()':| E:\\ IT-C ++ \\ snake.cpp ||在函数“ int main()”中:| E:\\IT-C++\\snake.cpp|11|error: could not convert 'infile.std::basic_ios<_CharT, _Traits>::eof [with _CharT = char, _Traits = std::char_traits]' to 'bool'| E:\\ IT-C ++ \\ snake.cpp | 11 |错误:无法将'infile.std :: basic_ios <_CharT,_Traits> :: eof [with _CharT = char,_Traits = std :: char_traits]'转换为'bool '| E:\\IT-C++\\snake.cpp|11|error: in argument to unary !| E:\\ IT-C ++ \\ snake.cpp | 11 |错误:一元参数中的参数|| ||=== Build finished: 2 errors, 0 warnings ===| || ===构建完成:2个错误,0个警告=== |

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
        string STRING;
    ifstream infile;
    infile.open ("names.txt");
        while(!infile.eof) // To get you all the lines.
        {
            getline(infile,STRING); // Saves the line in STRING.
            cout<<STRING; // Prints our STRING.
        }
    infile.close();

}
while(!infile.eof() )
              // ^^  missed. It's a member function of input output stream

You should start reading depending on the success of opening the file ie, return value of member function ifstream::is_open() . 您应该根据打开文件的成功开始阅读,即成员函数ifstream::is_open()返回值。

Should be 应该

while (getline(infile,STRING)) { // Saves the line in STRING.
    cout<<STRING; // Prints our STRING.
}

The error flags such as eof aren't set until after you've tried and failed to read past the end. 直到尝试并无法读取结束后,才会设置eof等错误标志。 The code as designed (even if the missing parentheses in infile.eof() are added) will process garbage on the final iteration when getline fails. 设计的代码(即使在infile.eof()中添加了缺少的括号infile.eof()也将在getline失败时在最后一次迭代中处理垃圾。 So you have to test the stream status after getline runs, as I show here. 因此,您必须在getline运行之后测试流状态,如我在此处所示。

The standard line-by-line file reading idiom goes like this: 标准的逐行文件阅读习惯是这样的:

std::string line;
std::ifstream infile("names.txt");

while (std::getline(infile, line))
{
  std::cout << "We read: " << line << std::endl;
}

No need to close the file explicitly, as that's done automatically when infile goes out of scope. 无需显式关闭文件,因为infile超出范围会自动完成。 Note that we never say eof , since that doesn't do what you want! 请注意,我们永远不会说eof ,因为那不能满足您的要求!

the eof is a function so you must write it as eof是一个函数,因此您必须将其编写为

infile.eof()

or you can put the getline into while condition 或者您可以将getline放入while条件

while( getline(infile,STRING))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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