首页 > 代码库 > C 字符输入输出和输入确认

C 字符输入输出和输入确认

1.前导程序

//一个菜单程序#include<stdio.h>char get_choice(void);char get_first(void);int get_int(void);void count(void);int main(void){    int choice;    void count(void);    while((choice=get_choice())!=q)    {        switch(choice)        {        case a:printf("Buy low,sell high.\n");            break;        case b:putchar(\a);            break;        case c:count();            break;        default:printf("program error!\n");            break;        }    }    printf("Bye.\n");    return 0;}void count(void){    int n,i;    printf("count how far? Enter an integer:\n");    n=get_int();    for(i=1;i<=n;i++)        printf("%d\n",i);    while(getchar()!=\n)        continue;}char get_choice(void){    int ch;    printf("Enter the letter your choice:\n");    printf("a.advice            b.bell\n");    printf("c.count             q.quit\n");    ch=get_first();    while((ch<a||ch>c)&&ch!=q)    {        printf("please respond with a,b,c,or q.\n");        ch=get_first();    }    return ch;}char get_first(void){    int ch;    ch=getchar();    while(getchar()!=\n)        continue;    return ch;}int get_int(void){    int input;    char ch;    while(scanf("%d",&input)!=1)    {        while((ch=getchar())!=\n)            putchar(ch);//剔除错误的输入        printf("is not an integer.\n");        printf("please enter an integer value,such as 25,-178,or 3:");    }    return input;}
View Code

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

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

3.终止键盘输入

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

4.重定向和文件

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

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

(1)使用缓冲输入

//猜数游戏#include<stdio.h>int main(void)/*{    int guess=1;    printf("Pick an integer from 1 to 100.I will try to guess it.\n");    printf("Respond with a y if my guess is right and with \n");    printf("an n if it is wrong.\n");    printf("UH....is your number %d?\n",guess);    while((getchar()!=‘y‘))             //获取用户响应并和y比较        printf("Well,then,is it %d?\n",++guess);    printf("I kenw I could do it!\n");    return 0;}*////*{    int guess=1;    printf("Pick an integer from 1 to 100.I will try to guess it.\n");    printf("Respond with a y if my guess is right and with \n");    printf("an n if it is wrong.\n");    printf("UH....is your number %d?\n",guess);    while((getchar()!=‘y‘))             //获取用户响应并和y比较    {        printf("Well,then,is it %d?\n",++guess);        while(getchar()!=‘\n‘)            continue;    }    printf("I kenw I could do it!\n");    return 0;}*///使用一个if语句来筛选掉其他响应{    char Response;//添加一个变量来存储响应!!!    int guess=1;    printf("Pick an integer from 1 to 100.I will try to guess it.\n");    printf("Respond with a y if my guess is right and with \n");    printf("an n if it is wrong.\n");    printf("UH....is your number %d?\n",guess);    //请注意,在修改的时候while判断语句也要改把值赋给变量Response    while((Response=getchar())!=y)             //获取用户响应并和y比较    {        if(Response==n)               //使用一个if语句            printf("Well,then,is it %d?\n",++guess);        else            printf("sorry,I understand only y or n.\n");//添加说明语句        while(getchar()!=\n)            continue;    }    printf("I kenw I could do it!\n");    return 0;}
猜数游戏

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

//一个关于I/O问题的程序//完成第一次打印染污后,程序提示输入第二组数据,可是在还没有做出响应之前程序就退出了,问题在哪里?#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:\n");    while((ch=getchar())!=\n)    {        scanf("%d%d",&rows,&cols);        display(ch,rows,cols);//调用函数打印字符        printf("Enter another character and two integers:\n");        printf("Enter a newline to quit.\n");    }    printf("Bye!\n");    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(\n);    }}//scanf()函数将换行符留在了输入队列中,getchar()并不跳过换行符,所以在循环的下一个周期,//在有机会输入第二组数据之前,这一换行符由getchar读取,然后赋值给ch,而ch为换行符则正是终止循环的条件/*#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:\n");    while((ch=getchar())!=‘\n‘)    {        if(scanf("%d%d",&rows,&cols)!=2)//判断输入            break;        display(ch,rows,cols);//调用函数打印字符        while(getchar()!=‘\n‘)//如果读取的是一个字符,则跳出            continue;        printf("Enter another character and two integers:\n");        printf("Enter a newline to quit.\n");    }    printf("Bye!\n");    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(‘\n‘);//结束本行,开始新的一行    }}*/
View Code

6.输入确认

//输入确认//在通常情况下,程序用户不总是遵循指令,在程序所期望的输入与实际获得的输入之间可能存在不匹配#include<stdio.h>#include<stdbool.h>//确认输入了一个整数int get_int(void)//确认范围的上下界是否有效bool bad_limits(int begin,int end,int low,int high);//计算从a到b之间的整数的平方和double sum_squares(int a,int b);int main(void){    const int MIN=-1000;    const int MAX=+1000int start;    int stop;    double answer;    printf("This program computs the sum of the squares of"        "integers in a range.\nThe lower bound should not"        "be less than -1000 and\nthe upper bound should not"        "be more than +1000.\nEnter the limits (enter 0 for"        "both limits to quit):\nlower limit:");    start=get_int();    printf("upper  limit:");    stop=get_int();    while(shart!=0||stop!=0)    {        if(bad_limits(start,stop,MIN,MAX))            printf("Please try again.\n");        else        {            answer=sum_squares(stare,stop);            printf("The sum of the squares of the integers from");            printf("from %d to %d is %g\n",start,stop,answer);        }        printf("Enter the limits(enter 0 for both limits to quit):\n");        printf("lower  limit:");        start=get_int();        printf("upper limit:");        stop=get_int();    }    printf("Done!\n");    return 0;}//使用get_int()函数来获取值int get_int(void){    int input;    char ch;    while(scanf("%d",&input)!=1)//用while循环来处理值    {        while((ch=getchar())!=\n)            putchar(ch);//剔除错误的输入        printf("is not an integer.\n please enter an integer value,such as 25,-178,or 3:");    }    return input;}//程序核心部分,进行实际计算double sum_squares(int a,int b){    double total=0;    int i;    for(i=a;i<=b;i++)        total+=i*i;    return total;}//bad_limits()函数来检查值的有效性bool bad_limits(int begin,int end,int low,int high){    bool not_good=false;    if(begin>end)    {        printf("%d isn‘t smaller than %d.\n",begin,end);        not_good=true;    }    if(begin<low||end<low)    {        printf("Values must be %d or greater.\n";low);        not_good=true;    }    if(begin>high||end>high)    {        printf("Values must be %d or less.\n",high);        not_good=true;    }    return not_good;}
View Code
  • 输入由字符构成,但scanf函数可以将输入转换成整数或浮点数,使用想%d和%f这样的说明符能限制可接受的输入字符类型,但getchar()和使用%c的scanf函数接受任何字符。

C 字符输入输出和输入确认