1. 程式人生 > 實用技巧 >C語言成長之路31:while迴圈獲取鍵盤輸入

C語言成長之路31:while迴圈獲取鍵盤輸入

宣告:本筆記基於B站UP主「來自程式設計師的暴擊」的「C語言成長之路」中對應課程;


while迴圈語法結構:

1 while (表示式)
2 {
3         語句;
4 }

當表示式為真時,則執行花括號裡面的語句,直到表示式不為真;


直接上練習操作一下~

  接收使用者輸入,如果使用者輸入的是大寫字母,則轉換成小寫,反之轉為大寫;

  如果是輸入數字,則原封不動輸出;

  如果輸入空格,則輸出space

附上一個呵呵老師的寫法:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <limits.h>
 4
#include <Windows.h> 5 6 void judge(char data){ 7 while (1){ 8 getchar(); 9 if (data >= 'A' && data <= 'Z'){ 10 printf("%c\n",data += 32); 11 } else if (data >= 97 && data <= 122){ 12 printf("%c\n",data -= 32
); 13 } else if (data >= 48 && data <= 57){ 14 printf("%c\n",data); 15 } else if (data == 32){ 16 printf("space\n"); 17 } else { 18 printf(" I dont know what are you talking about."); 19 } 20 } 21 } 22 23 void main(){
24 /* C語言成長之路31:while迴圈獲取鍵盤輸入 25 * 26 */ 27 char data = getchar(); 28 judge(data); 29 system("pause"); 30 };

這個寫法有點問題,main函式執行之後,data接收到輸入之後,就會帶著這個data去進入judge的迴圈了把,judge裡面的getchar()也只是做停頓作用?畢竟沒有賦值給變數,所以輸入的data是什麼,judge函式就會一直按照這個最初輸入的值去迴圈


然後我在這個基礎上進行了修改:不知道為啥,無論輸入什麼,最後都會列印

 I dont know what are you talking about.

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <limits.h>
 4 #include <Windows.h>
 5 
 6 void judge(char data){
 7     if (data >= 'A' && data <= 'Z'){
 8         printf("%c\n",data += 32);
 9     }
10     else if (data >= 97 && data <= 122){
11         printf("%c\n",data -= 32);
12     }
13     else if (data >= 48 && data <= 57){
14         printf("%c\n",data);
15     }
16     else if (data == 32){
17         printf("space\n");
18     }
19     else {
20         printf(" I dont know what are you talking about.\n");
21     }
22 }
23 
24 void main(){
25     /*  C語言成長之路31:while迴圈獲取鍵盤輸入
26      *
27      */
28     while (1){
29         printf("Please input something if you like~ \n");
30         char data = getchar();
31         judge(data);
32         Sleep(1000);
33     }
34 };