标准IO输入流API

在输入输出流概念当中有一个非常重要的概念:缓冲区

读和写是站在应用程序的角度来说的。输入的数据会先滞留到缓存区,有输出命令时回去缓存区拿数据。

1、cin cout

能根据类型 获取数据/输入数据

注:cin当遇到结束符(Space、Tab、Enter)时,会停止接受输入,结束符不会保存到数据中

int main()
{
	char mChar[10];
	int mInt;
	long mLong;
	double mDouble;
	float mFloat;

	cout << "输入一个字符数组:";
	cin >> mChar;
	cout << "输入一个int类型数据:";
	cin >> mInt;
	cout << "输入一个long类型数据:";
	cin >> mLong;
	cout << "输入一个double类型数据:";
	cin >> mDouble;
	cout << "输出一个float类型数据:";
	cin >> mFloat;

	cout << "字符数组:" << mChar << endl;
	cout << "int:" << mInt << endl;
	cout << "long:" << mLong << endl;
	cout << "double:" << mDouble << endl;
	cout << "float:" << mFloat << endl;

	cout << "Hello world!" << endl;
	system("pause");
	return 0;
}

2、cin.get()

无参、一个参数、多个参数,不能接受空格,输入结束条件是Enter键值

int main()
{
	char c;
	while ((c =cin.get()) != EOF)
	{
		cout << c << endl;
	}
	cout << "结束" << endl;
	system("pause");
	return 0;
}

//注:这里会出现阻塞,因为get()是一个字符一个字符读取的,但是结束命令是EOF,当没有接收到EOF命令时会一直等待读取造成阻塞。
//ctr+z  会产生一个 EOF(-1)

int main()
{
	char a, b, c;
	cin.get(a);
	cin.get(b);
	cin.get(c);

	cout << a << b << c << endl;
	cout << "链式编程" << endl;
	cin.get(a).get(b).get(c);
	cout << a << b << c << endl;
	system("pause");
	return 0;
}

3、cin.getline()可以接受空格

int main()
{
	char buf1[1024];
	char buf2[1024];
	cout << "输入带空格的字符串:";
	cin.getline(buf1, 1024);
	cout << buf1 << endl;

	cout << "试着输入代空格的字符串";
	cin >> buf2;
	cout << buf2 << endl;

	system("pause");
	return 0;
}

buf1和buf2的区别在于可不可以输出代空格的字符串,buf2中流提取操作符遇见空格停止提取输入流

4、cin.ignore() 跳过输入流中n个字符

int main()
{
	char buf1[256];
	char buf2[256];
	cout << "假如输入字符串aa  bbccdd:";
	cin >> buf1;
	cin.ignore(2);//忽略缓冲区中的两个空格"\n"
	cin >> buf2;
	//cin.getline(buf2, 256);
	cout << "buf1:" << buf1 << "buf2:" << buf2 << endl;
	system("pause");
	return 0;
}

5、cin.peek()查看输入流中的下一个字符

int main()
{
	int intchar;
	char buf1[256];
	char buf2[256];
	cout << "假如输入字符串aa  bbccdd:";
	cin >> buf1;
	cin.ignore(2);//忽略缓冲区中的两个空格"\n"
	int mInt = cin.peek();
	cout << "缓冲区若有数据,返回第一个数据的asc码:"<<mInt << endl;
	//缓冲区没有数据,就等待; 缓冲区如果有数据直接从缓冲区中拿走数据
	cin.getline(buf2, 256);
	cout << "buf1:" << buf1 << "buf2:" << buf2 << endl;

	intchar = cin.peek(); //没有缓冲区 默认是阻塞模式 
	cout << "缓冲区若有数据,返回第一个数据的asc码:" << intchar << endl;
	system("pause");
	return 0;
}

6、cin.putback ()

putback是将字符放回到输入流中,一般输入流中字符的长度是不变的。 putback会把cin刚刚“吃”进来的字符再“吐”回去,也就是说,下次cin的时候,刚刚得到的那个字符还会被输入。

#pragma warning(disable : 4996)
#include <iostream>
#include<string>
using namespace std;

//案例:输入的整数和字符串分开处理
int main()
{
	cout << "Please, enter a number or a word: ";
	char c = cin.get();

	if ((c >= '0') && (c <= '9')) //输入的整数和字符串 分开处理
	{
		int n; //整数不可能 中间有空格 使用cin >>n
		cin.putback(c);
		cin >> n;
		cout << "You entered a number: " << n << '\n';
	}
	else
	{
		string str;
		cin.putback(c);
		getline(cin,str) //字符串 中间可能有空格 使用 cin.getline();
		cout << "You entered a word: " << str << '\n';
	}	
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章