C++输入输出

C++中的一些常用输入输出:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

void win_io() //由控制台输入
{
	string line;
	cout << "输入一些字符后Enter:";
	//cin >> line;
	getline(cin, line); //输入可以带有空格
	cout << "从控制窗口读取的内容:" << line << endl; 
}

void file_io()  // 文件进行输入
{
	ifstream in_file("test.txt");

	string line;
	while(getline(in_file, line))
	{
		cout << line << endl; 
	}

	in_file.close();
}

void file_io_2() 
{
	fstream in_file("test.txt", ios_base::in | ios_base::out);

	const int MAX_LEN = 100;
	char line[MAX_LEN];
	while(in_file.getline(line, MAX_LEN))//也可使用infilne >> line
	//while(in_file >> line)
	{
		cout << line << endl; 
	}
	in_file.close();
	in_file.open("test.txt", ios_base::out);
	//in_file.seekg(ios::end);
	in_file << "nihao\n";
	in_file.close();
}

void buf_io() //由缓冲区进行输入
{
	istringstream ss("hello world");
	ostringstream oss;
	string word;
	while(ss >> word)
	{
		cout << word << endl;
		oss << word << endl;
	}
	cout << "oss " << oss.str();
}

void buf_io_2()
{
	stringstream ss;	
	ss << "hello world";

	string word;
	while(ss >> word)
	{
		cout << word << endl;
	}
}

void StringToInt(string str, int& i)//使用sstream实现类型转换同一个sstream对象类型转换时记得清空(.clear())
{
	stringstream ss;
	ss << str;
	ss >> i;
}

int main()
{

	win_io();
	//file_io();
	file_io_2();
	buf_io();
	//buf_io_2();

	string str("123");
	int i;
	StringToInt(str, i);
	cout << i << endl;

	system("pause");
	return 0;
}

扩展: http://www.cnblogs.com/azraelly/archive/2012/04/14/2446914.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值