String Streams (sstream)

本文介绍了C++中如何使用字符串流进行数据转换和格式化,包括istringstream、ostringstream和stringstream的用法。通过实例展示了如何创建并使用这些流来读取和写入字符串,特别强调了它们在不同类型数据间转换的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The iostream library supports in-memory input/output , in which a stream is attached to a string within the program’s memory. That string can be written to and read from using the iosteam input and output operators. The library defines three kinds of string streams:

1)        istringstream , derived from istream , reads from a string .

2)        ostringstream , derived from ostream , writes to a string .

3)        stringstream , derived from iostream , reads and writes a string .

[Note] To use any of these classes, we must include the sstream header.

 

stringstream-Specific Operations

stringstream   strm ;

Creates an unbound stringstream.

stringstream   strm(s) ;

Creates a stringstream that holds a copy of the string s.

strm.str()

Returns a copy of the string that strm holds.

strm.str(s)

Copies the string s into strm. Returns void.

 

stringstreamS   Provide Conversions and/or Formatting

One common use of stringstreamS is when we want to obtain automatic formatting across multiple data types. For example, we might have a collection of numeric values but want their string representation or vice versa. The sstream input and output operations automatically convert an arithmetic type into its corresponding string representation or back again.

 

Here we create an empty ostringstream object named format_message and insert the indicated text into that object. What’s important is that the int values are automatically converted to their printable string equivalents. The contents of format_message can be obtained from using the member str() to get the string from format_message.

 

[Note] To read input_string, we must parse the string into its component parts. We want the numeric values; to get them we must read (and ignore) the labels that are interspersed with the data we want.

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值