C ++:Getline在第一个空格处停止读取

时间:2016-09-12 01:04:55

标签: c++ string vector getline

基本上我的问题是我试图从.txt文件中读取数据和注释的数据,并将每一行存储到字符串向量中,但我的getline函数停止读取第一个空白字符,所以像(* comment *)这样的评论被分解为

str[0] = "(*";
str[1] = "comment";
str[2] = "*)";

这是我的getline函数的代码块:

int main() {
string line;
string fileName;
cout << "Enter the name of the file to be read: ";
cin >> fileName;

ifstream inFile{fileName};

istream_iterator<string> infile_begin {inFile};
istream_iterator<string> eof{};
vector<string> data {infile_begin, eof};
while (getline(inFile, line))
{
    data.push_back(line);
}

这就是.txt文件的样子:

101481
10974
1013
(* comment *) 0
28292
35040
35372
0000
7155
7284
96110
26175

我无法弄清楚为什么它不读全行。

1 个答案:

答案 0 :(得分:3)

这是因为您的代码没有使用std::getline来读取输入文件。

如果你仔细查看你的代码,你会看到在你达到这一点之前,你的代码在文件上构造istream_iterator<string>,并传递它,结束istream_iterator<string>vector的构造函数,这有效地将整个文件(一次一个以空格分隔的单词)吞入向量中。

当事情进入getline循环时,整个文件已经被读取,并且循环完全没有。对于当前的状况,你的getline并没有真正做任何事情。

完全摆脱涉及istream_iterator的内容,让getline完成预期的工作。

相关问题