C++文件流与字符串流

方便自己日后回顾和使用,也方便他人使用,我就不多说了。直接上代码。方便很多。


#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");

	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值