单字符I/O:getchar()和putchar()
1 #include<stdio.h> 2 3 int main(void) 4 { 5 char ch; 6 while ((ch = getchar()) != '#') 7 putchar(ch); 8 return 0; 9 }
1 #include<stdio.h> 2 3 int main(void) 4 { 5 char ch; 6 while ((ch = getchar()) != EOF) //EOF是代表文件结尾的标志 7 putchar(ch); 8 return 0; 9 }
重定向输入让程序使用文件而不是键盘来输入,重定向输出让程序输出至文件而不是屏幕。
1、重定向输入
假设已经编译了echo_eof.c程序,并把可执行版本放入一个名为echo_eof的文件中。运行该程序,输入可执行文件名:
echo_eof < words
2、 重定向输出
echo_eof > words
3、
假设希望制作一份mywords文件的副本,并命令为savewords。只需要输入:
echo_eof<mywords>savewords
echo_eof>mywords<savewords
#include<stdio.h> void display(char cr, int lines, int width); int main(void) { int ch; int rows, cols; printf("Enter a character and two integers: "); while ((ch = getchar()) != ' ') { if (scanf_s("%d %d", &rows, &cols) != 2) break; display(ch, rows, cols); while (getchar() != ' ') continue; printf("Enter another character and two integers; "); printf("Enter a newline to quit. "); } printf("Bye. "); return 0; } void display(char cr, int lines, int width) { int row, col; for (row = 1; row <= lines; row++) { for (col = 1; col <= width; col++) putchar(cr); putchar(' '); } }
输入由字符组成,但是scanf()函数可以使用说明符把输入转换成相应的类型。
例子
1 #include<stdio.h> 2 char get_choice(void); 3 void count(void); 4 char get_first(void); 5 int get_int(void); 6 7 int main(void) 8 { 9 int choice; 10 while ((choice = get_choice()) != 'q') { 11 switch (choice) 12 { 13 case 'a':printf("Buy low, sell high. "); 14 break; 15 case 'b':printf("OK"); 16 break; 17 case 'c':count(); 18 break; 19 default: printf("Program error! "); 20 break; 21 } 22 } 23 return 0; 24 } 25 26 char get_choice(void) 27 { 28 int ch; 29 printf("Enter the letter of your choice: "); 30 printf("a. advice b. state "); 31 printf("c. count q. quit "); 32 ch = get_first; 33 while ((ch <'a' || ch>'c') && ch != 'q') { 34 printf("Please response with a, b, c, or q. "); 35 ch = get_first(); 36 } 37 return ch; 38 } 39 char get_first(void) 40 { 41 int ch; 42 ch = getchar(); 43 while (getchar() != ' ') 44 continue; 45 return ch; 46 } 47 int get_int(void) 48 { 49 int input; 50 char ch; 51 while (scanf_s("%d", &input)!=1) { 52 while ((ch = getchar()) != ' ') 53 putchar(ch); 54 printf(" is not an integer. Please enter an integer value,such as 25."); 55 } 56 return input; 57 } 58 void count(void) 59 { 60 int n, i; 61 printf("Count how far?Enter an integer: "); 62 n = get_int(); 63 for (i = 1; i < n; i++) 64 printf("%d ", i); 65 while (getchar() != ' ') 66 continue; 67 }