1、流的概念
C++ 的 I/O 发生在流中,流是由若干字节组成的字节序列
输入流:从设备流向内存的字节流
输出流:从内存流向设备的字节流
标准输入流:从标准输入设备(键盘)流向内存的数据源
>>不接收空格、回车,以空格、回车做分隔符
(一)字符串流:以内存中的string对象/字符数组(c风格字符串)为IO的对象——将数据输出到内存的字符串存储区/从字符串存储区读入数据
字符串流类包括:
①定义在头文件<sstream>中:istringstream、ostringstream、stringstream,以string对象作为字符串
②定义在头文件<strstream>中:istrstream、ostrstream、strstream,以char数组作为字符串
使用字符串流类(基于①类)
(1)ostringstream类
进行格式化输入输出,将各种类型转换为string类型,只支持<<操作符
流插入运算符<<与ostringstream对象匹配,输出到ostringstream流对象中
#include<sstream>
#include<iostream>
using namespace std;
int main(){
ostringstream oss;//定义一个字符串输出流对象,未初始化
oss<<1.234;//将1.234输出到oss对象中 ==将1.234.转换成一个字符串
oss<<" ";//将空格字符串输出到oss对象中==将字符串常量转换为字符串“1.234 ” (1.234末尾加上空格)
oss<<1234;//字符串:“1.234 1234”
oss<<endl;// 字符串:“1.234 1234\n”
cout<<oss.str();//返回oss中的字符串并输出
oss.str(""); //清空为空字符串
oss<<3.1415926;
str2 = oss.str(); //str2复制为“3.1415926”
return 0;
}
(2)istringstream类
把一个已定义字符串中的以空格隔开的内容提取出来,只支持>>操作符
流提取运算符>>与istringstream对象匹配,从ostringstream流对象中提取数据输入到内存中
#include<sstream>
#include<iostream>
using namespace std;
int main(){
int a;
string str1;
string input = "abc 123 def 456 ghi 789";
istringstream iss(input);//通过构造函数对iss进行初始化==iss中存储字符串为input
while(iss>>str1>>a) //从iss中提取string类型数据str,提取int型数据a
cout<<str1<<" "<<a<<endl;
return 0;
}
(3)stringstream类
支持<<和>>操作符,是istringstream和ostringstream的综合
#include<sstream>
#include<iostream>
using namespace std;
int main(){
int a;
string input = "abc 123 def 456 ghi 789" ;
stringstream ss;
ss<<input;
while(ss>>str1>>a)
cout<<str1<<" "<<a<<endl;
return 0;
}
字符串流类的构造函数
字符串流类常用的成员函数
string str();//返回当前字符串流缓存区的字符串对象副本
void str(const string& s);//复制字符串s内容到字符串流缓存区关联的字符串对象中