stringstream在接受一个字符串流输入后,需要clear方能再次接受输入并使用,str("")用来清空缓存在stringstream中的内容。
正确代码:
#include <iostream>
#include <string>
#include <stdlib.h>
int main(int argc, char* argv[]) {
std::stringstream ss;
int a, b, c;
ss << "4";
ss >> a;
ss.clear();
ss << "2";
ss >> b;
ss.clear();
ss.str("");
ss << "567";
ss >> c;
std::cout << a << " " << b << " " << c << std::endl;
system("pause");
return 0;
}
输出结果:4 2 567
以上代码若没有ss.clear()的话输出结果:4 -858993460 -858993460
参考链接:
stringstream中的clear()与str()
-----------------------------------------------2020.2.12-----------------------------------------------
探究stringstream持续向一字符串变量传递值是否会影响原意:
int main(){
std::stringstream ss;
std::string str;
ss << 11;
ss >> str;
std::cout << str << std::endl;
ss.clear();
ss.str("");
//str = "";
ss << 22;
ss >> str;
std::cout << str << std::endl;
return 0;
}
无论中间的注释行是否被运行过,结果均是11换行22。证明在下次传递字符串值后字符串变量中的值被擦除后再写上了。