Monday 23 December 2019

fstream - eof problem c++



i am using Dev C++ on windows xp




#include 
#include
#include
using namespace std;

int main ()
{
string STRING;
ifstream infile;

infile.open ("sample.txt");
while(!infile.eof)
{
getline(infile,STRING);
cout< }
infile.close();

return 0;
}



this codes gives the following error



C:\C++\read.cpp: In function `int main()':

C:\C++\read.cpp:11: error: could not convert `infile.std::basic_ios<_CharT, _Traits>::eof [with _CharT = char, _Traits = std::char_traits]' to `bool'
C:\C++\read.cpp:11: error: in argument to unary !



i am not sure what is wrong here i cant compile the code
please help


Answer



If you change your loop to



  while(getline(infile,STRING))
{
cout< }



you avoid the possibility of reading the last value twice (see this SO post).


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...