reading the file

Hi !

how can i read a file in C++ (ubuntu) i'm using Ubuntu 11.04

my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
           
          string STRING;
          ifstream infile;
          infile.open("/home/ewa/Desktop/unix/data.txt");
       
          while(!infile.eof){
                            getline(infile,STRING);
                            cout<<STRING;
          }
      
          infile.close();
          system("pause");
}


and when i complie g++ file.cpp -o outfile, it gives me an error. Can anyone help.

Regards,

Ewa
and when i complie g++ file.cpp -o outfile, it gives me an error.


what error? can you paste the output?

also while(!infile.eof) is bad and I think it should be infile.eof()

use while(infile.good())

or while(!infile.rd_state())
Last edited on
Or do it like this
1
2
3
while(getline(infile,STRING)) {
	cout<<STRING;
}
otherwise you will run cout<<STRING; after EOF has been reached.
Hi Guys !

thanks for reply and the error i'm getting is:

read.cpp: in function int main()´:
read.cpp:12:16: error: argument of type `bool (std::basic_ios<char>::)() const´
does not match `bool`
read.cpp:12:16: error: in argument to unary !
read.cpp:18:16: error: 'System was not declared in this scope'

and after changing my code to
 
while(!infile.eof())


error is reduced to
read.cpp: in function 'int main()':
read.cpp:18:16: error: 'system' was not declare in this scope



thanks in advance

Regards,
Ewa
Last edited on
system (lower case 's' at the start) is a function that lives in the cstdlib header file. You'll have to #include it, although system is really, really not a good idea.

As it is, you're trying to use it to call the Windows command "pause", which will be a bit of a disaster given that you're not using Windows.
Last edited on
Topic archived. No new replies allowed.