The contents of file.txt are:
5 3
6 4
7 1
10 5
11 6
12 3
12 4
Where 5 3
is a coordinate pair.
How do I process this data line by line in C++?
I am able to get the first line, but how do I get the next line of the file?
ifstream myfile;
myfile.open ("text.txt");
Reading a file line by line in C++ can be done in some different ways.
[Fast] Loop with std::getline()
The simplest approach is to open an std::ifstream and loop using std::getline() calls. The code is clean and easy to understand.
[Fast] Use Boost's file_description_source
Another possibility is to use the Boost library, but the code gets a bit more verbose. The performance is quite similar to the code above (Loop with std::getline()).
[Fastest] Use C code
If performance is critical for your software, you may consider using the C language. This code can be 4-5 times faster than the C++ versions above, see benchmark below
Benchmark -- Which one is faster?
I have done some performance benchmarks with the code above and the results are interesting. I have tested the code with ASCII files that contain 100,000 lines, 1,000,000 lines and 10,000,000 lines of text. Each line of text contains 10 words in average. The program is compiled with
-O3
optimization and its output is forwarded to/dev/null
in order to remove the logging time variable from the measurement. Last, but not least, each piece of code logs each line with theprintf()
function for consistency.The results show the time (in ms) that each piece of code took to read the files.
The performance difference between the two C++ approaches is minimal and shouldn't make any difference in practice. The performance of the C code is what makes the benchmark impressive and can be a game changer in terms of speed.
Use
ifstream
to read data from a file:If you really need to read line by line, then do this:
But you probably just need to extract coordinate pairs:
Update:
In your code you use
ofstream myfile;
, however theo
inofstream
stands foroutput
. If you want to read from the file (input) useifstream
. If you want to both read and write usefstream
.Since your coordinates belong together as pairs, why not write a struct for them?
Then you can write an overloaded extraction operator for istreams:
And then you can read a file of coordinates straight into a vector like this:
First, make an
ifstream
:The two standard methods are:
Assume that every line consists of two numbers and read token by token:
Line-based parsing, using string streams:
You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use
getline()
after token-based extraction got you to the end of a line already.Although there is no need to close the file manually but it is good idea to do so if the scope of the file variable is bigger:
Expanding on the accepted answer, if the input is:
you will still be able to apply the same logic, like this: