如何读取特定文件fstream?
问题描述:
我有一个data.txt
文件,其内容是:如何读取特定文件fstream?
[exe1]
1 0 2 9 3 8
----------
[exe2]
----------
10 2 9 3 8:0
我想读第2行:1 0 2 9 3 8
。但我的输出只有1
。
我的代码:
#include <iostream>
#include <fstream>
#include <limits>
#include<string>
std::fstream& GotoLine(std::fstream& file, unsigned int num) {
file.seekg(std::ios::beg);
for (int i = 0; i < num - 1; ++i) {
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return file;
}
int main() {
using namespace std;
fstream file("data.txt");
GotoLine(file, 2);
std::string line2;
file >> line2;
std::cout << line2;
cin.get();
return 0;
}
什么是我的问题吗?对不起,我是编程新手。
答
file >> line2;
将停止读取第一个空格,因此只读取“1”,因为提取operator >>
使用空格作为分隔符。
您可能需要使用getline
为getline(file,line2)
答
输入操作>>
读取空格分隔字符串,如果你想阅读你需要使用一整行std::getline
:
std::string line2;
std::getline(file, line);
+0
是的,它的工作原理,谢谢 – dinhvan2804
它的工作原理,谢谢 – dinhvan2804