C语言之输入和输出

1.前导程序

复制代码
 1 //一个菜单程序
 2 #include<stdio.h>
 3 char get_choice(void);
 4 char get_first(void);
 5 int get_int(void);
 6 void count(void);
 7 int main(void)
 8 {
 9     int choice;
10     void count(void);
11 
12     while((choice=get_choice())!='q')
13     {
14         switch(choice)
15         {
16         case 'a':printf("Buy low,sell high.\n");
17             break;
18         case 'b':putchar('\a');
19             break;
20         case 'c':count();
21             break;
22         default:printf("program error!\n");
23             break;
24         }
25     }
26     printf("Bye.\n");
27     return 0;
28 }
29 
30 void count(void)
31 {
32     int n,i;
33     printf("count how far? Enter an integer:\n");
34     n=get_int();
35     for(i=1;i<=n;i++)
36         printf("%d\n",i);
37     while(getchar()!='\n')
38         continue;
39 }
40 
41 char get_choice(void)
42 {
43     int ch;
44     printf("Enter the letter your choice:\n");
45     printf("a.advice            b.bell\n");
46     printf("c.count             q.quit\n");
47     ch=get_first();
48     while((ch<'a'||ch>'c')&&ch!='q')
49     {
50         printf("please respond with a,b,c,or q.\n");
51         ch=get_first();
52     }
53     return ch;
54 }
55 
56 char get_first(void)
57 {
58     int ch;
59     ch=getchar();
60     while(getchar()!='\n')
61         continue;
62     return ch;
63 }
64 
65 int get_int(void)
66 {
67     int input;
68     char ch;
69 
70     while(scanf("%d",&input)!=1)
71     {
72         while((ch=getchar())!='\n')
73             putchar(ch);//剔除错误的输入
74         printf("is not an integer.\n");
75         printf("please enter an integer value,such as 25,-178,or 3:");
76     }
77     return input;
78 }
复制代码

2.单字符I/O:getchar()和putchar()

  • getchar和putchar()每次输入和输出一个字符。
  • 输入回显是大多数处理文本的程序的核心。
  • 他们不是真正的函数而是定义为预处理器宏。
  • 缓冲区完全缓冲和行缓冲。
复制代码
 1 //重复输入
 2 //putchar()函数和getchar()的使用
 3 #include<stdio.h>
 4 int main(void)
 5 {
 6     char ch;
 7 
 8     while((ch=getchar())!='#')
 9         putchar(ch);
10     return 0;
11 }
复制代码

3.终止键盘输入

  • 文件时一块存储信息的存储器区域,通常文件被保存在某种类别的永久存储器上。
  • C程序处理一个流而不是处理文件。
  • 计算机操作系统两种检测文件结尾的方法,1.在文件中放置一个特殊字符来标志结尾。2.让操作系统存储文件大小的信息。
  • C处理文件结尾的方法:#define EOF   (-1)   让getchar()函数在到达文件结尾时返回一个特殊值。eof并不是实际出现在文件中的一个符号。
复制代码
 1 //重复输入,知道文件的结尾
 2 //使用EOF来标记文件的结尾   ctral+z
 3 //每次按下回车键,处理缓冲区中存储的字符,并且打印一行副本。
 4 #include<stdio.h>
 5 int main(void)
 6 {
 7     char ch;
 8 
 9     while((ch=getchar())!=EOF)
10         putchar(ch);
11     return 0;
12 }
复制代码

4.重定向和文件

  • 重定向与操作系统而不是C相关联。
  • 输入重定向:echo_eof<words//运算符把words文件和stdin流关联起来,C将文件和I/O设备置于相同的地位,所以现在这个文件就是I/O设备。
  • 输出重定向:echo_eof>mywords//导致建立一个mywords的新文件供使用,然后将输出重定向到该文件。CTRL+Z
  • 组合重定向:重定向运算符的顺序无关紧要。1.只能将一个可执行程序和一个数据文件连接起来。2. 输入和输出只能来自或定向到一个文件。
  • 管道运算符‘|’可以将一个程序的输出与第二个程序的输入连接起来。
复制代码
 1 //打开一个文件并显示其内容
 2 #include<stdio.h>
 3 #include<stdlib.h>//为了适应exit()
 4 int main(void)
 5 {
 6     int ch;
 7     FILE*fp;
 8     char fname[50];//用于存放文件名
 9 
10     printf("Enter the name of the file:");
11     scanf("%s",fname);
12     fp=fopen(fname,"r");//打开文件以供读取
13     if(fp==NULL)//尝试打开文件失败
14     {
15         printf("Failed to open file.Bye\n");
16         exit(1);//终止程序
17     }
18     //getc(fp)从打开的文件中获取一个字符
19     while((ch=getc(fp))!=EOF)
20         putchar(ch);
21     fclose(fp);  //关闭文件
22     return 0;
23 }
复制代码

5.创建一个更友好的用户界面

(1)使用缓冲输入

复制代码
 1 //猜数游戏
 2 #include<stdio.h>
 3 int main(void)
 4 /*{
 5     int guess=1;
 6     printf("Pick an integer from 1 to 100.I will try to guess it.\n");
 7     printf("Respond with a y if my guess is right and with \n");
 8     printf("an n if it is wrong.\n");
 9     printf("UH....is your number %d?\n",guess);
10     while((getchar()!='y'))             //获取用户响应并和y比较
11         printf("Well,then,is it %d?\n",++guess);
12     printf("I kenw I could do it!\n");
13     return 0;
14 }*/
15 //
16 /*{
17     int guess=1;
18     printf("Pick an integer from 1 to 100.I will try to guess it.\n");
19     printf("Respond with a y if my guess is right and with \n");
20     printf("an n if it is wrong.\n");
21     printf("UH....is your number %d?\n",guess);
22     while((getchar()!='y'))             //获取用户响应并和y比较
23     {
24         printf("Well,then,is it %d?\n",++guess);
25         while(getchar()!='\n')
26             continue;
27     }
28     printf("I kenw I could do it!\n");
29     return 0;
30 }*/
31 //使用一个if语句来筛选掉其他响应
32 {
33     char Response;//添加一个变量来存储响应!!!
34     int guess=1;
35     printf("Pick an integer from 1 to 100.I will try to guess it.\n");
36     printf("Respond with a y if my guess is right and with \n");
37     printf("an n if it is wrong.\n");
38     printf("UH....is your number %d?\n",guess);
39     //请注意,在修改的时候while判断语句也要改把值赋给变量Response
40     while((Response=getchar())!='y')             //获取用户响应并和y比较
41     {
42         if(Response=='n')               //使用一个if语句
43             printf("Well,then,is it %d?\n",++guess);
44         else
45             printf("sorry,I understand only y or n.\n");//添加说明语句
46         while(getchar()!='\n')
47             continue;
48     }
49     printf("I kenw I could do it!\n");
50     return 0;
51 }
复制代码

(2)混合输入数字和字符

复制代码
 1 //一个关于I/O问题的程序
 2 //完成第一次打印染污后,程序提示输入第二组数据,可是在还没有做出响应之前程序就退出了,问题在哪里?
 3 #include<stdio.h>
 4 void display(char cr,int lines,int width);
 5 int main(void)
 6 {
 7     int ch;//要打印的字符
 8     int rows,cols;
 9     printf("Enter a character and two integers:\n");
10     while((ch=getchar())!='\n')
11     {
12         scanf("%d%d",&rows,&cols);
13         display(ch,rows,cols);//调用函数打印字符
14         printf("Enter another character and two integers:\n");
15         printf("Enter a newline to quit.\n");
16     }
17     printf("Bye!\n");
18     return 0;
19 }
20 
21 void display(char cr,int lines,int width)
22 {
23     int row,col;//请注意这里的变量和主函数变量的区别
24 //用一个双重循环打印字符
25     for(row=1;row<=lines;row++)
26     {
27         for(col=1;col<=width;col++)
28             putchar(cr);
29         putchar('\n');
30     }
31 }
32 //scanf()函数将换行符留在了输入队列中,getchar()并不跳过换行符,所以在循环的下一个周期,
33 //在有机会输入第二组数据之前,这一换行符由getchar读取,然后赋值给ch,而ch为换行符则正是终止循环的条件
34 /*
35 #include<stdio.h>
36 void display(char cr,int lines,int width);
37 int main(void)
38 {
39     int ch;//要打印的字符
40     int rows,cols;
41     printf("Enter a character and two integers:\n");
42     while((ch=getchar())!='\n')
43     {
44         if(scanf("%d%d",&rows,&cols)!=2)//判断输入
45             break;
46         display(ch,rows,cols);//调用函数打印字符
47         while(getchar()!='\n')//如果读取的是一个字符,则跳出
48             continue;
49         printf("Enter another character and two integers:\n");
50         printf("Enter a newline to quit.\n");
51     }
52     printf("Bye!\n");
53     return 0;
54 }
55 
56 void display(char cr,int lines,int width)
57 {
58     int row,col;
59     for(row=1;row<=lines;row++)
60     {
61         for(col=1;col<=width;col++)
62             putchar(cr);
63         putchar('\n');//结束本行,开始新的一行
64     }
65 }
66 */
复制代码

6.输入确认

复制代码
 1 //输入确认
 2 //在通常情况下,程序用户不总是遵循指令,在程序所期望的输入与实际获得的输入之间可能存在不匹配
 3 #include<stdio.h>
 4 #include<stdbool.h>
 5 //确认输入了一个整数
 6 int get_int(void)
 7 //确认范围的上下界是否有效
 8 bool bad_limits(int begin,int end,int low,int high);
 9 //计算从a到b之间的整数的平方和
10 double sum_squares(int a,int b);
11 int main(void)
12 {
13     const int MIN=-1000;
14     const int MAX=+100015     int start;
16     int stop;
17     double answer;
18 
19     printf("This program computs the sum of the squares of"
20         "integers in a range.\nThe lower bound should not"
21         "be less than -1000 and\nthe upper bound should not"
22         "be more than +1000.\nEnter the limits (enter 0 for"
23         "both limits to quit):\nlower limit:");
24     start=get_int();
25     printf("upper  limit:");
26     stop=get_int();
27     while(shart!=0||stop!=0)
28     {
29         if(bad_limits(start,stop,MIN,MAX))
30             printf("Please try again.\n");
31         else
32         {
33             answer=sum_squares(stare,stop);
34             printf("The sum of the squares of the integers from");
35             printf("from %d to %d is %g\n",start,stop,answer);
36         }
37         printf("Enter the limits(enter 0 for both limits to quit):\n");
38         printf("lower  limit:");
39         start=get_int();
40         printf("upper limit:");
41         stop=get_int();
42     }
43     printf("Done!\n");
44     return 0;
45 }
46 
47 //使用get_int()函数来获取值
48 int get_int(void)
49 {
50     int input;
51     char ch;
52 
53     while(scanf("%d",&input)!=1)//用while循环来处理值
54     {
55         while((ch=getchar())!='\n')
56             putchar(ch);//剔除错误的输入
57         printf("is not an integer.\n please enter an integer value,such as 25,-178,or 3:");
58     }
59     return input;
60 }
61 
62 //程序核心部分,进行实际计算
63 double sum_squares(int a,int b)
64 {
65     double total=0;
66     int i;
67 
68     for(i=a;i<=b;i++)
69         total+=i*i;
70     return total;
71 }
72 
73 //bad_limits()函数来检查值的有效性
74 bool bad_limits(int begin,int end,int low,int high)
75 {
76     bool not_good=false;
77     if(begin>end)
78     {
79         printf("%d isn't smaller than %d.\n",begin,end);
80         not_good=true;
81     }
82     if(begin<low||end<low)
83     {
84         printf("Values must be %d or greater.\n";low);
85         not_good=true;
86     }
87     if(begin>high||end>high)
88     {
89         printf("Values must be %d or less.\n",high);
90         not_good=true;
91     }
92     return not_good;
93 }
复制代码
  • 输入由字符构成,但scanf函数可以将输入转换成整数或浮点数,使用想%d和%f这样的说明符能限制可接受的输入字符类型,但getchar()和使用%c的scanf函数接受任何字符。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值