我刚刚阅读了C ++中的stringstream并实现了一个简单的程序。
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int num;
stringstream sso;
string str;
//integer to string
cin >> num;
sso << num;
sso >> str;
cout << "String form of number : " << str << endl;
//string to integer
cin >> str;
sso << str;
sso >> num; //num still has value from previous integer to string????
cout << "Integer form of string (+2) :" << (num + 2) << endl;
return 0;
}
这是输出:
12
String form of number : 12
44
Integer form of string (+2) :14
我得到了不正确的输出,因为num
它没有得到更新,并且仍然保持先前计算的旧值。我在做什么愚蠢的错误?
您应该清除两次使用之间的字符串流,因为在第一次使用时已设置了eofbit:
sso.clear();
sso.str("");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句