Home  >  Article  >  Backend Development  >  How to read a file using C++?

How to read a file using C++?

PHPz
PHPzOriginal
2024-06-05 20:31:00791browse

Reading files in C++ requires two functions: ifstream to open the file stream, and getline to read line by line. Specific steps include: 1. Use ifstream to create a file stream. 2. Check whether the file is opened successfully. 3. Use getline to read the file contents line by line. 4. Process each row of data. 5. Close the file.

How to read a file using C++?

How to read files using C++

Reading files in C++ involves two main functions: ifstream and getline. The ifstream function creates an input file stream object, while the getline function reads the contents of the file line by line.

Code Example

The following code example demonstrates how to read from a file using ifstream and getline:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
  // 打开输入文件
  ifstream inputFile("input.txt");

  // 检查文件是否打开成功
  if (inputFile.is_open()) {
    // 逐行读取文件内容
    string line;
    while (getline(inputFile, line)) {
      // 在这里处理每一行数据
      cout << line << endl;
    }

    // 关闭文件
    inputFile.close();
  } else {
    cout << "无法打开文件!" << endl;
  }

  return 0;
}

Practical case

Suppose we have a text file named input.txt which contains the following content:

姓名:John Smith
年龄:25
性别:男

We can use the above code to read from this file content and displayed on the console:

姓名:John Smith
年龄:25
性别:男

The above is the detailed content of How to read a file using C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn