文章目录
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 );