c++读取txt文本数据
时间: 2023-12-12 18:01:58 浏览: 32
读取txt文本数据可以使用C++中的文件流,具体步骤如下:
1. 打开文件流,可以使用 ifstream 类:
```cpp
#include <fstream>
using namespace std;
ifstream infile("filename.txt");
```
2. 读取文件内容,可以使用 getline 函数:
```cpp
string line;
while (getline(infile, line))
{
// 处理每行数据
}
```
3. 关闭文件流:
```cpp
infile.close();
```
完整的代码示例:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile("data.txt");
if (!infile.is_open())
{
cout << "Failed to open file!" << endl;
return 0;
}
string line;
while (getline(infile, line))
{
cout << line << endl;
}
infile.close();
return 0;
}
```
其中,data.txt 是要读取的文件名,可以根据实际情况进行修改。