一、背景
使用fstream和sstream头文件读取文本文件。实现按行读取或者按照空格分隔读取。
二、代码
- 按行读取文件内容
int main() {
ifstream input_file("file.txt");
if (!input_file.good()) {
cout << "open fail." << endl;
return -1;
} else {
cout << "open successful." << endl;
}
stringstream input_stream;
input_stream << input_file.rdbuf();
input_file.close();
string str;
while (getline(input_stream, str)) {
cout << str << endl;
}
return 0;
}
file.txt内容:
hello world.
1 2 3
1 hello 2 world. 3
输出内容:
open successful.
hello world.
1 2 3
1 hello 2 world. 3
- 按空格分隔读取文件内容
只需要将while循环中的代码改为:
while (input_stream >> str) {
cout << str << endl;
}
file.txt内容不变。
输出内容为:
open successful.
hello
world.
1
2
3
1
hello
2
world.
3