【发布时间】:2011-06-21 03:00:51
【问题描述】:
istream 有 >> 运算符,但它会像跳过空格一样跳过新行。如何将仅 1 行中的所有单词的列表放入向量(或任何其他方便使用的内容)中?
【问题讨论】:
istream 有 >> 运算符,但它会像跳过空格一样跳过新行。如何将仅 1 行中的所有单词的列表放入向量(或任何其他方便使用的内容)中?
【问题讨论】:
一种可能性(虽然比我想要的要详细得多)是:
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>());
【讨论】:
std::copy 而不是 Foo Bah 的 for 循环?
std::copy()。使用std::vector的构造函数。
我建议使用getline 将行缓冲到string,然后使用stringstream 来解析string 的内容。例如:
string line;
getline(fileStream, line);
istringstream converter(line);
for (string token; converter >> token; )
vector.push_back(token);
小心在 C++ 中使用 C 字符串读取函数。 std::string I/O 函数更安全。
【讨论】:
你可以调用 istream::getline -- 会读入一个字符数组
例如:
char buf[256];
cin.getline(buf, 256);
如果您想对行中的各个令牌使用流兼容的访问器,请考虑使用 istringstream
【讨论】: