Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Read file line by line using ifstream in C++

The contents of file.txt are:
5 3
6 4
7 1
10 5
11 6
12 3
12 4


Where 5 3 is an organised pair. How would I deal with this information line by line in C++?
I'm ready to get the first line, however, how would I get the following line of the file?

ifstream myfile;
myfile.open ("file.txt");
by

3 Answers

espadacoder11
First, make an ifstream:

#include <fstream>
std::ifstream infile("thefile.txt");
The two standard methods are:

1. Assume that every line consists of two numbers and read token by token*:

int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}

2. *Line-based parsing, using string streams
:

#include <sstream>
#include <string>

std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int a, b;
if (!(iss >> a >> b)) { break; } // error

// process pair (a,b)
}

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.
kshitijrana14
Use ifstream to read data from a file:

std::ifstream input( "filename.ext" );

If you really need to read line by line, then do this:

for( std::string line; getline( input, line ); )
{
...for each line in input...
}

But you probably just need to extract coordinate pairs:

int x, y;
input >> x >> y;

Update:

In your code you use ofstream myfile;, however the o in ofstream stands for output. If you want to read from the file (input) use ifstream. If you want to both read and write use fstream.
RoliMishra
Since your coordinates belong together as pairs, why not write a struct for them?

struct CoordinatePair
{
int x;
int y;
};


Then you can write an overloaded extraction operator for istreams:

std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
is >> coordinates.x >> coordinates.y;

return is;
}


And then you can read a file of coordinates straight into a vector like this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
char filename[] = "coordinates.txt";
std::vector<CoordinatePair> v;
std::ifstream ifs(filename);
if (ifs) {
std::copy(std::istream_iterator<CoordinatePair>(ifs),
std::istream_iterator<CoordinatePair>(),
std::back_inserter(v));
}
else {
std::cerr << "Couldn't open " << filename << " for reading\n";
}
// Now you can work with the contents of v
}

Login / Signup to Answer the Question.