標籤:float choice div 類型 oat putc 標準 取數 鍵盤
學習總結
1、緩衝區分為完全緩衝區(fully buffered)I/O和行緩衝區(line-buffered)I/O。對完全緩衝輸入來說,當緩衝區滿的時候會被清空(緩衝區內容發送至其目的地)。這類型的緩衝區通常出現在檔案輸入中。對於行緩衝I/O來說,遇到一個換行字元時將被清空緩衝區,鍵盤輸入是標準的行緩衝區。
2、EOF是C對檔案結尾的一個標識,在stdio.h標頭檔中定義,#define EOF (-1)。在使用鍵盤輸入時,可以通過Ctrl+D類比EOF訊號:
#include <stdio.h>int main(){ int ch; while((ch=getchar())!=EOF){ putchar(ch); } return 0;}
Abc[Enter]
abc
123[Ctrl+D]123
3、>和<都是重新導向運算子,必須是可執行程式加檔案,拿以上程式為例子:
執行:./test > abc
輸入:
abcdefg[Enter]1234567[Enter]
執行:cat abc
輸出:
abcdefg
1234567
4、除了以上重新導向運算子還有>>運算子,該運算子可使您的一個現有檔案的末尾追加資料。還有管道運算子(|),其實這些運算子都是Unix和Linux上的運算子。
執行:./test >> abc
輸入:
hijklmn[Enter]
執行:cat abc
輸出:
abcdefg
1234567
hijklmn
執行:./test | grep aaa
輸入:aaabbbccc[Enter]dddeeefff[Enter]ggghhhaaa[Enter]
輸出:
aaabbbccc
ggghhhaaa
5、在建立與使用者對話的程式時,需要考慮到所有的邊界問題,例如程式只需要使用者輸入a、b、c、d的時候,萬一使用者輸入量其他的且一大串的字元會如何處理等等情況。還有程式同時需要getchar進行字元輸入和使用scanf進行數字輸入,這兩個函數中的每一個都能很好的完成其工作,但它們不能很好地混合在一起,這是因為getchar讀取每個字元,包括空格、定位字元和分行符號,而scanf在讀取數字時則會跳過空格、定位字元和分行符號。
6、編程題(題8)
1 #include <stdio.h> 2 3 int getChoice(void); 4 int getFirst(void); 5 6 int main(){ 7 int ch,t,y; 8 float a,b; 9 int c;10 char sa[10],sb[10];11 12 ch=getChoice();13 if(ch==113){14 return 0;15 }else{16 printf("Enter first number:");17 scanf("%s",sa);18 while(sscanf(sa,"%f",&a)!=1){19 printf("%s is not an number.\nPlease enter a number.such as 2.5, -1.78E8, or 3:",sa);20 scanf("%s",sa);21 }22 printf("Enter second number:");23 scanf("%s",sb);24 while(sscanf(sb,"%f",&b)!=1||(ch==100&&b==0)){25 if(ch==100&&b==0){26 printf("Enter a number other than 0:");27 }else{28 printf("%s is not an number.\nPlease enter a number.such as 2.5, -1.78E8, or 3:",sb);29 }30 scanf("%s",sb);31 }32 }33 34 if(ch==97){35 printf("%s+%s=%.1f\n",sa,sb,a+b);36 }else if(ch==98){37 printf("%s-%s=%.1f\n",sa,sb,a-b);38 }else if(ch==99){39 printf("%s*%s=%s\n",sa,sb,a*b);40 }else{41 printf("%s/%s=%.1f\n",sa,sb,a/b);42 }43 44 return 0;45 }46 47 int getChoice(void){48 int ch;49 printf("Enter the operation of your choice:\n");50 printf("a. add b. subtract\n");51 printf("c. multiply d.divide\n");52 printf("q. quit\n");53 ch=getFirst();54 while(ch!=97&&ch!=98&&ch!=99&&ch!=100&&ch!=113){55 printf("Please enter a right choice:\n");56 ch=getFirst();57 }58 59 60 }61 62 int getFirst(void){63 int ch;64 ch=getchar();65 while(getchar()!=10)66 return 0;67 return ch;68 }
運行結果:
Enter the operation of your choice:
a. add b. subtract
c. multiply d.divide
q. quit
f
Please enter a right choice:
d
Enter first number:qqq
qqq is not an number.
Please enter a number.such as 2.5, -1.78E8, or 3:1
Enter second number:0
Enter a number other than 0:1
1/1=1.0
【C語言學習】《C Primer Plus》第8章 字元輸入/輸出和輸入確認