【C++】几种输入

cin

最简单方便的输入。
头文件iostream,记得要加std

代码写法:cin>>变量1>>变量2;
输入方式:不同变量用空格隔开。

#include<iostream>
using namespace std;
int a;
char b;
int main(){
	cin>>a>>b;
	printf("%d %c", a, b);
	return 0;
}
1 a
1 a
--------------------------------
Process exited after 2.279 seconds with return value 0
请按任意键继续. . .

scanf()

C语言的原生输入方式,格式化输入,是最快的
头文件cstdio,用iostream也可以。

代码写法:scanf(“占位符1 占位符2”, &替换符1, &替换符2);
输入格式:按照格式化输入写法来输入。

常用的占位符符号

变量类型占位符写法
int%d
long long%lld
double%lf
long double%Lf
char%c
stringchar数组%s
#include<cstdio>
int a;
char b;
int main(){
	scanf("%d%c", &a, &b);
	//scanf()函数特性:整形变量和字符型变量输入时可以不用空格隔开。 
	printf("%d %c", a, b);
	return 0;
}
1a
1 a
--------------------------------
Process exited after 3.271 seconds with return value 0
请按任意键继续. . .

另外,再补充一个常用的不常用写法%[]:扫描字符集合
举个非常常见例子,当要输入一整行一整行(且包含空格)的字符串(或char数组)时,就可以集合内可以直接写:^\n

#include<cstdio>
char a[1024];
int main(){
	scanf("%[^\n]", &a); 
	printf("%s", a);
	return 0;
}
abc 123
abc 123
--------------------------------
Process exited after 11.37 seconds with return value 0
请按任意键继续. . .

以上是两种常规的输入方式,接下来的输入可就精彩了。

getchar()

读取单个字符,数据经过缓冲区带回显
头文件cstdio,用iostream也可以。
其实,a=gerchar();等价于scanf("%c", &a);,我们在控制台输入数据时,控制台会先将数据放到缓冲区,当按下enter后再将其释放,让程序接收到。(cinscanf都是如此)

#include<cstdio>
char a;
int main(){
	a=getchar();
	printf("%c", a);
	return 0;
}
x
x
--------------------------------
Process exited after 6.003 seconds with return value 0
请按任意键继续. . .

getche()

读取单个字符,数据不经过缓冲区带回显
头文件conio.h
getche()的特点就是我们输入数据时,数据不经过缓冲区,直接传给程序。

#include<cstdio>
#include<conio.h>
char a;
int main(){
	a=getche();
	printf("%c", a);
	return 0;
}
xx
--------------------------------
Process exited after 1.217 seconds with return value 0
请按任意键继续. . .

getch()

读取单个字符,数据不经过缓冲区不带回显
头文件conio.h
getcha()的特点就是我们输入数据时,数据不仅不经过缓冲区、直接传给程序,就连我们自己都看不到自己输入的什么。

#include<cstdio>
#include<conio.h>
char a;
int main(){
	a=getch();
	printf("%c", a);
	return 0;
}
x
--------------------------------
Process exited after 0.886 seconds with return value 0
请按任意键继续. . .

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值