35~C++ IO输入流

1. 输入流对象 cin

object std::cin
extern std::istream cin;

2. 输入流检查规则

cin >> val

从输入数据流的开始位置找到匹配val类型的数据:如果找不到返回0

3. 数据读取举例

3.1 读取整数

#include <iostream>
using namespace std;
int main()
{
	int val;
	if(cin >> val)
	{
		cout << "Got: "<< val << endl;
	}
	else
	{
		cout << "exception" << endl;
	}
	return 0;
}
/*
输入:23
输出:
23
Got: 23

输入:sd
输出:
sd
exception
*/

3.2 连续读取

/*
输入:
12 sd
输出:
12sd
*/
#include <iostream>
using namespace std;
int main()
{
	int val;
	string something;
	cin >> val >> something;
	
	cout << val << something << endl;
	return 0;
}

3.3 考虑进制

/*
输入:0x64 64
输出:100 100
*/
#include <iostream>
using namespace std;
int main()
{
	int val1 , val2;

	cin >> hex;

	cin >> val1 >> val2;
	
	cout << val1 << " " << val2 << endl;
	return 0;
}

4. 测试状态

io流状态
在这里插入图片描述

4.1 测试举例

/*
输入:df sd
输出:
cin fail
*/
#include <iostream>
using namespace std;
int main()
{
	int val1 , val2;

	cin >> val1 >> val2;
	
	if(!cin)
	{
		if(cin.eof())
		{
			cout << "cin end" << endl;
		}
		if(cin.bad())
		{
			cout << "cin bad" << endl;
		}
		if(cin.fail())
		{
			cout << "cin fail" << endl;
		}
	}

	
	return 0;
}

4.2 清空状态

#include <iostream>
using namespace std;
int main()
{
	int val1 , val2;

	cin >> val1 >> val2;

	cin.clear();

	
	if(!cin)
	{
		
	       
		if(cin.eof())
		{
			cout << "cin end" << endl;
		}
		if(cin.bad())
		{
			cout << "cin bad" << endl;
		}
		if(cin.fail())
		{
			cout << "cin fail" << endl;
		}
	}


	
	return 0;
}

5. 非格式化读取

5.1 读取一个字符

#include <iostream>
using namespace std;
int main()
{
	char val;
	cin.get(val);
	cout << val << endl;

	return 0;
}

5.2 读取一行数据

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

6. 其它接口

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值