2

istream>>运算符,但它会像跳过空格一样跳过新行。如何仅将 1 行中的所有单词列表放入向量(或任何其他方便使用的内容)中?

4

3 回答 3

2

一种可能性(虽然比我想要的要详细得多)是:

std::string temp;
std::getline(your_istream, temp);

std::istringstream buffer(temp);
std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
                                std::istream_iterator<std::string>());
于 2011-02-04T03:33:33.253 回答
1

我建议使用getline将行缓冲到 astring中,然后使用 astringstream来解析它的内容string。例如:

string line;
getline(fileStream, line);

istringstream converter(line);
for (string token; converter >> token; )
    vector.push_back(token);

小心在 C++ 中使用 C 字符串读取函数。std::stringI/O 功能更安全。

于 2011-02-04T03:34:20.280 回答
0

您可以调用 istream::getline -- 将读入字符数组

例如:

char buf[256];
cin.getline(buf, 256);

如果您想对行中的各个令牌使用流兼容的访问器,请考虑使用 istringstream

于 2011-02-04T03:31:14.423 回答