C++ primer 习题8-3 15 16

加深和熟练对输入输出流的运用。。。

#include<iostream>
using namespace std;
istream&get(istream &in)
{
	int val;
	cout<<"输入:";
	while(in>>val,!in.eof())
	{
		if(in.bad())throw("eroor。。");
		if(in.fail())
		{
			cerr<<"Try again!!!"<<endl;
			in.clear();
			in.setstate(istream::eofbit);//这句为什么不可以呢??
//            in.ignore(1,' ');
			continue;
		}
		cout<<val<<endl;
	}
		in.clear();
		return in;
}
int main()
{
	get(cin);
	int vall;
	cin>>vall;
	cout<<"vall="<<vall<<endl;
	return 0;
}

疑问:返回的in应该正常,为什么main函数中的cin不能输入呢???


8-15

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
istream&get(istringstream &in,string &w)
{
//	istringstream val;
     in.str(w);//这句很关键
     string val;
	cout<<"输入:";
	while(in>>val,!in.eof())
	{
		if(in.bad())throw("eroor。。");
		if(in.fail())
		{
			cerr<<"Try again!!!"<<endl;
			in.clear();
//			in.setstate(istream::eofbit);//这句为什么不可以呢??
            in.ignore(1,' ');
			continue;
		}
		cout<<val<<endl;
	}
		in.clear();
		return in;
}
int main()
{
	istringstream sin;
	string w="wo men dou shi hao hai zi";
	get(sin,w);
	int vall;
	cin>>vall;
	cout<<"vall="<<vall<<endl;
	return 0;
}

8-16

#include<iostream>
#include<vector>
#include<sstream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main()
{
	ifstream fin;
	fin.open("source.cpp");
	if(!fin){cerr<<"Open error..."<<endl;exit(1);}
	string line;
	vector<string> vec;
	while(!fin.eof())
	{
		getline(fin,line);
		vec.push_back(line);
	}
	vector<string>::iterator iter=vec.begin();
	string word;
	while(iter!=vec.end())
	{
		istringstream sin(*iter);
		while(sin>>word)
		cout<<word<<endl;
//       while(!sin.eof()){sin>>word;cout<<word<<endl;}
		++iter;
	}


	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值