๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

C++ Reading Files

File input is the reading of data from a file into a program. The program can then work with values that were stored in the file.

Reading numbers and adding them

The file data.txt holds one number on each line. The loop reads each number and adds it to the sum.

#include <iostream>
#include <fstream>

int main() {
  std::ifstream in("data.txt");
  int number;
  int sum = 0;
  while (in >> number) {
    sum += number;
  }
  std::cout << "Sum: " << sum << "\n";
  return 0;
}

Reading lines with a count

std::getline reads one name at a time from names.txt. The count rises by one for each line, and each line prints with its count.

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::ifstream in("names.txt");
  std::string line;
  int count = 0;
  while (std::getline(in, line)) {
    count++;
    std::cout << count << ": " << line << "\n";
  }
  return 0;
}

Testing a file that is not there

The program tries to open a file name that does not exist. The stream tests false, so the program prints a plain line and ends.

#include <iostream>
#include <fstream>

int main() {
  std::ifstream in("missing.txt");
  if (!in) {
    std::cout << "Could not open the file\n";
    return 0;
  }
  std::cout << "The file opened\n";
  return 0;
}

Example

#include <iostream>
#include <fstream>
#include <string>

int main() {
  std::ifstream in("scores.txt");
  std::string name;
  int score;
  std::string bestName;
  int bestScore = 0;
  while (in >> name >> score) {
    if (score > bestScore) {
      bestScore = score;
      bestName = name;
    }
  }
  std::cout << "Top scorer: " << bestName << " " << bestScore << "\n";
  return 0;
}

Key points

  • std::ifstream is the type for a stream that reads from a file.
  • The >> operator reads the next value from an input file stream.
  • A read with >> skips spaces and line breaks between values.
  • std::getline reads one whole line from a file stream.
  • A reading loop ends when the stream has no more data.
  • The test if (!in) is true when the file did not open.
  • A program can handle a missing file and end in the normal way.

In this example, the loop reads a name and a score from each line of scores.txt. A line with a higher score replaces the best name and the best score. The last print shows Mina with the top score of 95.

Note

The file names in this lesson are relative names.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A program opens a file that does not exist. What is the value of the test if (!in)?