ca78a_c++_字符串流在内存中的输入输出(速度快)

/*ca78a_c++_字符串流在内存中的输入输出
**字符串流:在内存中的输入输出.(在内存中进行,速度快)
**文件流 :是对文件进行输入和输出.(在磁盘里面进行)
istringstream(输入),ostringstream(输出),stringstream(输入输出)
**字符串流stringstream特定的操作
stringstream strm;
stringstream strm(s);
strm.str()
strm.str(s)
**stringstream提供的转换和格式化,字符转字符,数字自动转数字
while (isstream >> word) //>>流输入操作符,一个一个的单词读取,空格作为单词分割的标志
welcome to discuss
txwtech@163.com
*/

 1 /*ca78a_c++_字符串流在内存中的输入输出
 2 **字符串流:在内存中的输入输出.(在内存中进行,速度快)
 3 **文件流 :是对文件进行输入和输出.(在磁盘里面进行)
 4 istringstream(输入),ostringstream(输出),stringstream(输入输出)
 5 **字符串流stringstream特定的操作
 6 stringstream strm;
 7 stringstream strm(s);
 8 strm.str()
 9 strm.str(s)
10 **stringstream提供的转换和格式化,字符转字符,数字自动转数字
11  while (isstream >> word) //>>流输入操作符,一个一个的单词读取,空格作为单词分割的标志
12 welcome to discuss
13 txwtech@163.com
14 */
15 
16 #include <iostream>
17 #include <fstream>
18 #include <sstream>//stringstream(输入输出)头文件
19 #include <vector>
20 
21 using namespace std;
22 
23 int main()
24 {
25     cout << "hello" << endl;
26 
27     //文件输出流
28     ofstream ofs("test.txt");
29     ofs << "hello!" << endl;
30     ofs.close();
31     
32     //字符串输出流
33     ostringstream oss;
34     oss << "字符串流hello!" << endl;//放在内存里面的
35     cout <<"字符串流里面的信息:"<< oss.str() << endl;//oss.str()查看流对象里面的字符串
36 
37     //例子2:
38     string fileName, s;
39     vector<string> svec;
40     istringstream isstream;//输入字符串流
41     string word;
42     fileName = "book1.txt";
43     ifstream inFile(fileName.c_str());
44     if (!inFile)
45     { 
46         cout << "文件打开错误:!!!" << __FILE__ << " " << __DATE__ << endl;
47         return -1;
48     }
49         
50     while (getline(inFile, s))
51         svec.push_back(s);
52     inFile.close();
53     for (vector<string>::const_iterator iter = svec.begin(); iter != svec.end(); ++iter)
54     {
55         //cout << *iter << endl;
56         //把vector数据放入到输入字符串流里面
57         isstream.str(*iter);
58         while (isstream >> word)//>>流输入操作符,空格为间隔符号。一个一个单词的读取显示
59         {
60             //cout << word << endl;
61         }
62         isstream.clear();//字符串流清空,继续下一次循环
63     }
64     ostringstream format_message;//(字符串流)保存到内存,处理速度快
65     format_message << "姓名: " << "张飞" << "
" << "age: " << 22<< "
" << "weight: " <<88.8 << "
";
66     cout << "show ZhangFei:
" << format_message.str() << endl;
67 
68     cout << "读取字符串流里面的数据" << endl;
69     string dump;
70     string name;
71     int age;
72     double weight;
73     istringstream input_istring(format_message.str());
74     input_istring >> dump; //"姓名:" ,format_message << "姓名: " 的姓名后面要有空格,才会读取准确
75     input_istring >> name;//"张飞"
76     input_istring >> dump;//"age: "
77     input_istring >> age;//22
78     input_istring >> dump;//"weight: "
79     input_istring >> weight;//88.8
80     cout <<"name: "<< name <<" age:"<< age <<" weight: "<< weight << endl;
81 
82     return 0;
83 }
欢迎讨论,相互学习。 txwtech@163.com
原文地址:https://www.cnblogs.com/txwtech/p/12298666.html