在c語言中,運用for迴圈和getchar(),希望當輸入回車時,跳出這個迴圈,並且各種平臺適用,
- 2021-11-22
#include
int main()
{
char c;
for (;;) //無限迴圈
{
c=getchar(); // 讀一字元
if (c==‘\n’)break; //若是 新行鍵 跳出 迴圈
else
printf(“The char is %c —— %#x\n”,c,c); //否則列印這個字元和它的鍵值
}
printf(“The char is new-line —— %#x”,c,c);
return 0;
}
====
例如輸入:
123 +# abYZ
輸出:
The char is 1 —— 0x31
The char is 2 —— 0x32
The char is 3 —— 0x33
The char is —— 0x20
The char is + —— 0x2b
The char is # —— 0x23
The char is —— 0x20
The char is a —— 0x61
The char is b —— 0x62
The char is Y —— 0x59
The char is Z —— 0x5a
The char is new-line —— 0xa
透過getchar返回的值是10, 要使用 x==10 break;
下面是解釋:
前幾天,群裡有人問getch()和getchar()的區別,原因是他鍵入enter後,前者返回13,而後者返回10。程式碼如下:
#include
#include
int main()
{
int ch, cha;
ch = getch();
cha = getchar();
printf(“ch=%d, cha=%d\n”,ch,cha);
getch();
return 0;
}
enter enter
ch=13, cha=10
這裡特別說明一下,這段程式碼是在windows平臺下,才會產生如上所說的差異。原因是windows平臺下enter鍵會產生兩個跳脫字元 \r\n, 因此,getch()讀到 \r 時就會返回他的ascii碼13。
奇怪的問題是為什麼getchar()會返回10呢?前面不是說過返回第一個字元嗎?
這的確會讓人費解。實際上產生這個結果的原因是,getchar()把輸入的 \r\n 轉換成了 \n ,所以返回的是 \n 的ascii碼 10。為什麼會這樣呢?因為前面說過getchar()是c語言標準庫函式,而在unix系統中enter鍵只產生 \n 。順便說一下,在mac os中enter鍵將產生 \r ,同樣也會被替換成 \n。這樣,不管在什麼平臺下,getchar()都會得到相同的結果,所以說getchar()標準庫函式。
上一篇:如何使產後肚子和大腿變瘦
下一篇:命犯天煞是什麼意思