Getting input from file

Hi,
What command/code do I need to get input from a text file to
a) read the first n lines
b) read until certain characters
c) read until the end of the file?
Thanks
http://www.cplusplus.com/doc/tutorial/files/

The tutorial is a bit dated but it will teach you what you need to know. Just keep in mind that there is generally no reason to ever use .open() or .close().
Last edited on
As LB mentioned a link above have all you need to do in a,b,c.

a) read the first n lines
use below function to read the line:
getline ( myfile, line );

b) read until certain characters
use :
1
2
3
4
5
6
7
8
9
10
11
12
13
      

ifstream myfile ("example.txt");
string str; 
 while( !myfile.eof() )
{
 instream>> str;
 if(str == certainChar)
   // STOP reading file
else
  // print str
 }            


c) read until the end of the file?
use eof() to know the end of files comes or not.


Last edited on
while( !myfile.eof() )
Looping on eof() is almost never a right choice. It works too late. EOF is set only after stream could not provide character it was asked.

You should always loop on input operation. Alternatively you should check for error condition immediately after read and before actually using value you got, as it might be invalid.

For b and c you should provide more use cases: what to do with stuff read from file in c? Is there one character or sequence of characters in b? What to do with characters before searched, after and searched for characters?

Most of these problems are solvable in two ways: first, long and hard: read file character-by-character and im[plement searching yourself; or second: use standard library and solve almost everything in one line.
Last edited on
For reading lines of the file:

1
2
3
4
5
6
7
8
string FileLines[10];
int x = 0;

while (getline (file,line)) {

       FileLines[x] = line;
       x++;
}


Now every line in the file is stored from top to bottom in the string array FileLines.
Topic archived. No new replies allowed.