stringstream
2019.02.25 11:15:03字数 71阅读 299
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin).
注意: 小心stringstream.str()字符串用法的陷阱
streamstring在调用str()时,会返回临时的string对象。而因为是临时的对象,所以它在整个表达式结束后将会被析构。由于紧接着调用的c_str()函数将得到的是这些临时string对象对应的C string,而它们在这个表达式结束后是不被引用的,进而这块内存将被回收而可能被别的内容所覆盖
接口函数
clear() — to clear the stream
str() — to get and set string object whose content is present in stream.
operator << — add a string to the stringstream object.
operator >> — read something from the stringstream object,
应用
- 统计字符串中的单词数目
- 统计字符串中的词频
- 去除字符串中的空格
- 字符串转换为数字
示例来源
// A program to demonstrate the use of stringstream
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s = "12345";
// object from the class stringstream
stringstream geek(s);
// The object has the value 12345 and stream
// it to the integer x
int x = 0;
geek >> x;
// Now the variable x holds the value 12345
cout << "Value of x : " << x;
return 0;
}
3万+

被折叠的 条评论
为什么被折叠?



