【C++ Primer | 08】IO库

C++的输入输出分为三种:

(1)基于控制台的I/O

(2)基于文件的I/O

(3)基于字符串的I/O

istringstream

描述:从流中提取数据,支持 >> 操作

这里字符串可以包括多个单词,单词之间使用空格分开

 1 #include <iostream>   
 2 #include <sstream>   
 3 using namespace std;
 4 int main()
 5 {
 6     istringstream istr("1 56.7");
 7 
 8     cout << istr.str() << endl;//直接输出字符串的数据 "1 56.7"   
 9 
10     string str = istr.str();//函数str()返回一个字符串   
11     cout << str << endl;
12 
13     int n;
14     double d;
15 
16     //以空格为界,把istringstream中数据取出,应进行类型转换   
17     istr >> n;//第一个数为整型数据,输出1   
18     istr >> d;//第二个数位浮点数,输出56.7  
19     cout << d << endl;
20     cout << n << endl;
21     d = 0;
22     n = 0;
23 
24     //假设换下存储类型   
25     istr >> d;//istringstream第一个数要自动变成浮点型,输出仍为1   
26     istr >> n;//istringstream第二个数要自动变成整型,有数字的阶段,输出为56   
27 
28     //测试输出   
29     cout << d << endl;
30     cout << n << endl;
31     return 1;
32 }

输出结果:

举例2:把一行字符串放入流中,单词以空格隔开。之后把一个个单词从流中依次读取到字符串

 1 #include <iostream>   
 2 #include <sstream>   
 3 using namespace std;  
 4 int main()  
 5 {  
 6     istringstream istr;  
 7     string line,str;  
 8     while (getline(cin,line))//从终端接收一行字符串,并放入字符串line中   
 9     {  
10         istr.str(line);//把line中的字符串存入字符串流中   
11         while(istr >> str)//每次读取一个单词(以空格为界),存入str中   
12         {  
13             cout<<str<<endl;  
14         }  
15     }  
16     return 1;  
17 }  

输出结果:

ostringstream类

描述:把其他类型的数据写入流(往流中写入数据),支持 << 操作

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9655190.html