关于stringstream重复使用时的问题

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】中。

你可能感兴趣的:(C++)