Can anyonhe tell me how to do this step for text files? |
If you have used
cin
to get input from the keyboard, then you'll already be familiar with the syntax - though in any real-world examples there will always be little things to trip up the unwary.
To read a line typed by the user at the keyboard, you would have
1 2
|
string line;
getline(cin, line);
|
To do the same thing with a text file, just replace cin with the name of the input file stream.
1 2 3
|
ifstream infile("input.txt"); // declare and open input
string line;
getline(infile, line);
|
Similarly, to read numbers from the text file, put something like:
1 2 3 4
|
double a;
int b;
double c;
infile >> a >> b >> c;
|
Of course in your program you should choose better names for the variables rather than line, a, b and c.
There are a couple more things to consider if you want to do this repeatedly in a loop. Firstly, the
>>
extraction operator will ignore any leading whitespace, then extract as far as the end of the variable, but importantly it leaves any trailing whitespace (such as the newline character '\n') untouched. That can cause problems when using
getline()
which will stop reading after it finds a newline character.
There is also a blank line in the input file which separates each group of items. One way to deal with both trailing newline or a blank line is to use
ignore()
. Another is to use the
ws
manipulator which can actually be simpler to use but it gives rather less control and may not always be appropriate.
http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/reference/istream/istream/ignore/
http://www.cplusplus.com/reference/istream/ws/