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 |
string 或char数组 | %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
后再将其释放,让程序接收到。(cin
、scanf
都是如此)
#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
请按任意键继续. . .