MFC使用ifstream读取txt文件时选择读取一行
要选择读取txt文件的特定行,您需要按行读取文件并在读取时跟踪行号。
以下是基本思路:
-
打开文件并创建ifstream对象。
-
使用getline() 函数读取文件中的每一行,同时用一个计数器变量跟踪行号。
-
如果当前行数等于您要读取的行数,则处理该行。
-
重复步骤2和3,直到读取到文件的末尾。
下面是一个示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file; // 创建 ifstream 对象
file.open("example.txt"); // 打开文件
string line;
int count = 0; // 初始化计数器
// 从文件中按行读取数据
while (getline(file, line))
{
count++;
if (count == 3) // 选择要读取的行数
{
// 处理您要读取的行
cout << "第三行:" << line << endl;
}
}
// 关闭文件
file.close();
return 0;
}