Skip to main content

12.5) Reading Values From A Text File


Imagine that you have a single column of integer values, stored in a file called test.data. You could read these values into a vector like so:

ifstream infile("test.data");
if (not infile.is_open()) {
  cerr << "Error: cannot open file" << endl;
  exit(1);
}
vector<int> data;
int value;
while (infile >> value) {
  data.push_back(value);
}

How it works:

  • A stream extraction operation can be used as the test in a while loop
  • The loop will run while the operation succeeds
  • The body of the loop simply needs to use the extracted values - e.g., storing them in a vector

A similar approach will work for files containing multiple columns of data. For example, if you had a file containing the coordinates of points in 3D space, as three columns of floating-point values separated by whitespace, then the following loop would read the coordinates of each point:

double x, y, z;
while (infile >> x >> y >> z) {
  // do something with coordinates of point
}