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

标签 c++ string vector getline

基本上我的问题是我试图从一个充满数字和注释的 .txt 文件中读取数据并将每一行存储到一个字符串 vector 中,但是我的 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

我不明白为什么它不读整行。

最佳答案

这是出于非常简单的原因,您的代码没有使用 std::getline读取输入文件。

如果您非常仔细地查看您的代码,您会发现在您到达那一点之前,您的代码构造了一个 istream_iterator<string>。在文件上,并通过传递它和结尾 istream_iterator<string> vector 的值的构造函数,这有效地将整个文件(一次一个以空格分隔的单词)吞入 vector 中。

当事情发展到 getline 时循环,整个文件已经被读取,循环什么都不做。你的getline就目前的情况而言,实际上并没有做任何事情。

摆脱涉及 istream_iterator 的那些东西s,完全,简单地让getline完成预期的工作。

关于C++:Getline 在第一个空格处停止读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442140/

相关文章:

c++ - 关于Abstract pure virtual function Runtime Segment Fault的问题

连接 2 个字符串并返回一个新指针

c++ - 打开多个输入文件

c++ - 将标准函数对象转换回仿函数结构

python - 计算字符串中的连续字符

string - 不同旋转字符串的数量

c++ - std::vector 在重新分配时无论如何调用包含对象的析构函数?

c++ - vector::reserve和经典内存分配之间的内存分配差异

java - Java调用 "call"方法时无法存储Vector数据

c++ - 在模板中初始化静态成员