Mark As Completed Discussion

Reading from Files

To read data from a file in C++, you can use the ifstream class from the fstream library. The ifstream class provides functions to read data from a file.

Here's an example code that demonstrates how to read data from a file using ifstream:

TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3
4int main() {
5  std::ifstream file("example.txt");
6  std::string line;
7
8  if (file.is_open()) {
9    while (getline(file, line)) {
10      std::cout << line << std::endl;
11    }
12    file.close();
13  } else {
14    std::cout << "Unable to open file" << std::endl;
15  }
16
17  return 0;
18}

In the code above, we include the necessary libraries iostream and fstream. We then declare an ifstream object named file and pass the name of the file we want to read as a parameter. We also declare a std::string variable named line to store each line of the file.

Inside the if statement, we check if the file is successfully opened using the is_open() function. If the file is open, we use a while loop and the getline() function to read each line of the file and store it in the line variable. We then print the line to the console using cout. Once we have finished reading all the lines, we close the file using the close() function.

If the file cannot be opened, we print an error message. It's important to handle such cases to prevent errors in your program.

This code demonstrates how to read the contents of a file line by line. You can modify it to suit your specific needs, such as parsing data or performing calculations on the read data. Remember to always check if the file is successfully opened before reading from it to avoid errors.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment