c++从文件读取数据时怎么以空格为结束条件
时间: 2023-11-22 13:52:31 浏览: 145
可以使用C++中的输入流对象,例如`ifstream`,以空格为分隔符读取文件中的数据。具体方法如下:
1. 打开文件并创建`ifstream`对象。
```c++
#include <fstream>
using namespace std;
ifstream infile("data.txt"); // 打开文件
```
2. 使用输入流对象的`>>`运算符连续读取文件中的数据,以空格为分隔符。
```c++
int num;
while (infile >> num) { // 以空格为分隔符读取文件中的整数
// 处理读入的数据
}
```
在这个例子中,当读取到一个非数字字符时(例如空格、回车、制表符等),输入流对象就会停止读取并返回,因此空格就成为了数据的分隔符。
3. 关闭文件。
```c++
infile.close(); // 关闭文件
```
完整代码示例:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream infile("data.txt"); // 打开文件
int num;
while (infile >> num) { // 以空格为分隔符读取文件中的整数
cout << num << " "; // 输出读入的整数
}
infile.close(); // 关闭文件
return 0;
}
```
假设`data.txt`文件中的内容为:
```
12 34 56 78 90
```
运行上述代码输出:
```
12 34 56 78 90
```
阅读全文
相关推荐

















