//字符串流
//字符串输入输出流有三种istringstream,ostringstream,stringstream
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
#include<vector>
using namespace std;
int main()
{
//对比
//cout是流对象。ostream
cout << "hello" << endl;//输出到屏幕上
//ofs是文件输出流对象
//ofstream ofs("test.txt");
//ofs << "hello" << endl;
//ofs.close();//文件流,建立一个文件并且输出字符在里面
//字符串输出流
ostringstream oss;
oss << "hello" << endl;//输出到内存里
cout << "显示字符串流里边的字符串" << oss.str() << endl;
string filename, s;
vector<string> svec;
istringstream isstream;//输入字符串流
string word;
filename = "test.txt";
ifstream inFile(filename.c_str());//用输入文件流读字符串
if (!inFile)
{
return -1;
}
while (getline(inFile, s))
{
svec.push_back(s);
}
inFile.close();
for (vector<string>::const_iterator iter = svec.begin(); iter != svec.end(); ++iter)
{
/*cout << *iter << endl;*/
isstream.str(*iter);//把字符放进流里
while (isstream >> word)//isstream是输入字符串流,每次读入一个单词到word里,把每一行拆分
{
cout << word << endl;
}
isstream.clear();//流结束了就要清空
}
ostringstream format_message;//数据保存在字符串流里
format_message << "姓名:" <<"张飞"<< "\n" << "年龄:" <<88<< "\n"<<"体重:"<< 66 <<"\n"<<endl;//都会变成字符串
cout << "显示\n" << format_message.str() << endl;//保存在内存里速度更快,比保存在硬盘和文件里速度好很多
//如果我们现在要去读这个流
//把姓名,年龄体重都读出来
string dump;
string 姓名;
int 年龄;
double 体重;
istringstream input_istring(format_message.str());//把输出字符串流的字符串创建一个输入字符串流
input_istring >> dump;//扔掉姓名
input_istring >> 姓名;//读到姓名
input_istring >> dump;
input_istring >> 年龄;
input_istring >> dump;
input_istring >> 体重;
cout << "读到的结果" << endl;
cout << 姓名 << endl;
cout << 年龄 << endl;
cout << 体重 << endl;
system("pause");
return 0;
//使用方法和文件流很像,都是标准IO口里的对象,字符串流是在内存里操作
}
//数据结构和算法是说如何在内存中操作的
string流
最新推荐文章于 2020-09-05 16:52:24 发布