stringstream

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; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值