简体   繁体   中英

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?

The Error I get is:

E:\\IT-C++\\snake.cpp||In function '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|error: in argument to unary !| ||=== Build finished: 2 errors, 0 warnings ===|

#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() .

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. The code as designed (even if the missing parentheses in infile.eof() are added) will process garbage on the final iteration when getline fails. So you have to test the stream status after getline runs, as I show here.

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. Note that we never say eof , since that doesn't do what you want!

the eof is a function so you must write it as

infile.eof()

or you can put the getline into while condition

while( getline(infile,STRING))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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