您的位置:首页 > 其它

关于stringstream重复使用时的问题

2015-03-07 05:34 218 查看
1.clear()与str("")

测试代码

string s1("333.444.555");

string s2("666.777.888");

stringstream ss;

string w1, w2;

ss << s1;

getline(ss, w1, '.');

cout << w1 << " " << ss.str() << endl;

ss.clear(); // ss.str("");

ss << s2;

getline(ss, w2, '.');

cout << w2 << " " << ss.str() << endl;

测试截图

clear()并没有清空string buff

将上述代码中ss.clear()替换为ss.str("");

测试截图

可见string buff被清空了

原因:

str("")的原型和作用

void str (const string& s);

sets s as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence.

clear()的原型和作用

void clear (iostate state = goodbit);

Set error state flags

Sets a new value for the stream's internal error state flags.

其实这段代码也是存在问题的,在别的编译器上可能会报错。在【关于stringstream重复使用时的问题2】中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: