【C語言學習】《C Primer Plus》第8章 字符輸入/輸出和輸入確認
學習總結
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章 字符輸入/輸出和輸入確認