【发布时间】:2015-02-09 21:59:44
【问题描述】:
我正在使用stringstream 将数字字符串转换为整数。我不知道为什么后面的代码不起作用。有人可以向我解释为什么我总是得到相同的 tmp 变量值吗?
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>
int main() {
std::ifstream input("input.txt");
std::ofstream output("output.txt");
std::string str = "", line;
std::stringstream ss;
int tmp;
while (std::getline(input, line)) {
for (int i = 0, l = line.size(); i < l; i++) {
if (isdigit(line[i]))
str += line[i];
}
ss << str;
// gets int from stringstream
ss >> tmp;
output << str << ' ' << tmp << std::endl;
str = "";
// stringstream clearing
ss.str("");
}
return 0;
}
【问题讨论】:
-
resetting a stringstream 的可能重复项
-
@inetknght 与 ss.clear() 它可以工作。但为什么呢?
-
Don't use while(!input.eof())。相反,将循环更改为
while (std::getline(input, line)) { -
@NikitaShelimov
clear()重置位置指示器和任何错误标志
标签: c++ string stl stringstream