scanf()函數結構
scanf()函數被用來從stdin讀入數據,並且在程序中儲存數據。默認,這個stdin流是來着鍵盤輸入。
scanf()的函數結構與printf()類似:
int i;
scanf("%d",&i);
%d 是一個佔位符,說明這個地方有一個變量,並且爲整型變量
& 是個地址符,表明這個地方放置地址,&i的意思就是 i這個變量的地址
int i;
float j;
scanf("%d%f", &i, &j);
當輸入兩個以上的變量的時候,使用空格來分隔這兩個變量
需要注意的是對變量的定義要和輸入時的類型保持一致:
#include <stdio.h>
int main(void)
{
int i;
printf("please input a number: ");
scanf("%f",&i);
printf("You inputed number is %f\n",i);
}
此時得到的結果會是一個意想不到的值
另外,不要使用float值作爲輸入類型,請一律使用double,然後在佔位符的地方設置爲%lf,這樣纔可以得到正確的結果。
#include <stdio.h>
int main(void)
{
double i;
printf("please input a number: ");
scanf("%lf",&i);
printf("You inputed number is %lf\n",i);
}
scanf()字符串輸入:
char str[100];
scanf("%s", str);
scanf會接收100字符內的所有輸入,直到出現空格空格,例如Hello World,實際上只是輸入了Hello.
scanf還有更靈活的應用,scanf("%[etp]",str),此時scanf只接受e\t\p三個字符,只要不存在這三個字符,立即就完成輸入
please input a string : eetttsdfasfd
You inputed string is eettt
please input a string : tpaejk
You inputed string is tp
scanf("%[^etp]",str) 則與前面的相反,只要遇到e\t\p就會終止
#include <stdio.h>
int main(void)
{
int a, b;
scanf("%dm%d", &a, &b);
printf("%d %d\n", a, b);
return 0;
}
請注意在%d %d之間有一個m,所以在輸入的時候,我們也必須輸入一個m作爲間隔
當我們想輸入日期的時候,我們就可以使用%d/%d/%d
返回值
scanf()正常的返回值是1,因此當返回值不爲1時,說明函數未被正確執行