3

i am using Dev C++ on windows xp

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

int main ()
{
    string STRING;
    ifstream infile;
    infile.open ("sample.txt");
        while(!infile.eof)
        {
            getline(infile,STRING); 
            cout<<STRING; 
        }
    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<char>]' 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

user721776
  • 33
  • 1
  • 3
  • 5
    Not directly related to your question, but Dev-C++ is really outdated. Try using [Code::Blocks](http://www.codeblocks.org/downloads/26) with MingW or [Visual Studio Express](http://www.microsoft.com/express/Downloads/#2010-Visual-CPP) instead – Firas Assaad Apr 23 '11 at 14:06
  • thanks for the suggestion @ Firas Assaad , i have used visual studio express , but its slows down my poor pc, i will try code::blocks – user721776 Apr 23 '11 at 14:15

3 Answers3

10

std::ifstream::eof is a function that returns a bool. Thsu you have to call it like

infile.eof()
Oswald
  • 31,254
  • 3
  • 43
  • 68
10

If you change your loop to

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

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

Community
  • 1
  • 1
jonsca
  • 10,218
  • 26
  • 54
  • 62
  • what if i use get() to read single char like infile.get() , then how do i control the loop without using infile.eof() ? – user721776 Apr 23 '11 at 14:38
  • @user721776: So long as you assign the result to an `int` (`std::istream::int_type`) and not a `char` (`std::istream::char_type`) then on all reasonable platforms you can reliably test against `EOF` (`std::istream::traits_type::eof()`) as your loop condition. – CB Bailey Apr 23 '11 at 14:48
  • @user721776 infile.get() with no arguments returns an int that you can test against *the value* EOF. In contrast, `infile.get(c)` where c is a character returns an istream object that you can check to see if it's null in the while loop condition just like with getline. – jonsca Apr 23 '11 at 14:49
8

You forgot the () after the eof.

wheaties
  • 35,646
  • 15
  • 94
  • 131