【发布时间】:2017-05-23 00:26:26
【问题描述】:
我有一个文本文件,其中包含一系列两个字符串,每行用冒号分隔。
我使用 getline 来抓取整行,然后使用字符串流来拆分两个字符串并将它们放到一个向量上。该代码在第一次通过时运行良好,它完美地抓住了字符串。然后在 while 循环的第二次传递之后,它不会获取新的输入。由于某种原因,字符串流似乎保留了原始的第一个值。
if (infile.is_open()) {
std::stringstream ss;
std::string current_line;
std::string tempProxy;
std::string tempPort;
while (std::getline(infile, current_line)) {
ss << current_line;
std::getline(ss, tempProxy, ':');
std::getline(ss, tempPort);
std::cout << tempProxy << " and " << tempPort << std::endl;
}
知道为什么它不想在除第一次迭代之外的任何通道中从 current_line 中获取字符串吗?
【问题讨论】:
-
为什么
ss,tempProxy和tempPort在外部范围内?为什么ss不是std::istringstream简单地从current_line构造? -
这很奇怪,我认为在循环外构造一次字符串流并使用 >> 运算符为其提供一个新流将比每次通过循环构造它更有效。