方便自己日后回顾和使用,也方便他人使用,我就不多说了。直接上代码。方便很多。
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
/*******************************************************
字符 串流
字符串流:内存中的输入输出
istringstream
ostringstream
stringstream
字符串流stringstream特定的操作
stringstream strm;
stringstream strm(s);
strm.str() : 返回该字符串流中的字符串
strm.str(s)
stringstream提供的转换和格式化
*******************************************************/
void main() {
/*----------------------------------------------------------------*/
//字符串输出流 -- 内存里
ostringstream oss;
oss << "hello!" << endl;
//oss.str() --- 返回该字符串流中的字符串
cout << "显示字符串 流中的字符串 oss.str():" << oss.str() << endl;
cout << "----------------------------\n";
ostringstream format_message;
//注意,前一个字符串与后一个字符串中间要有一个"空格",否则,字符串流会将其视为一个字符,可比较
//"姓名:" << " " << "张飞" << "\n"
//<< "年龄: " << 22 << "\n"
format_message << "姓名:" << " " << "张飞" << "\n"
<< "年龄: " << 22 << "\n" //将整形、double转变为字符串
<< "体重: " << 88.5 << "\n";
cout << "显示张飞 : \n" << format_message.str() << endl;
string dump;
string name;
int age;
double weight;
istringstream input_istring(format_message.str());
input_istring >> dump; //丢掉
input_istring >> name;
input_istring >> dump;
input_istring >> age; //将字符串自动转换为对应的int、double
input_istring >> dump;
input_istring >> weight;
cout << "读到的结果:" << endl;
cout << "名字 " << name << endl;
cout << "年龄 " << age << endl;
cout << "体重 " << weight << endl;
cout << "-------------------------------------------------------\n";
/*----------------------------------------------------------------*/
//文件流
string fileName;//用于存放文件名
string s;//用于存放读取文件中的字符串
vector<string> vt_string;
fileName = "d:\\use.txt";
ifstream inFile(fileName.c_str());//一个文件流
if (!inFile) {
return;
}
//getline(文件流,字符串) --- 读取一行
while (getline(inFile, s)) {
vt_string.push_back(s);
}
inFile.close();
//迭代器输出
for (vector<string>::const_iterator iter = vt_string.begin(); iter != vt_string.end(); iter++) {
cout << *iter << endl;
}
/*----------------------------------------------------------------*/
system("pause");
}