<C语言>编写一个程序,该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行数目以及读取的所有其他字符数目。

来源:互联网 发布:淘宝买迷你睡莲哪家好 编辑:程序博客网 时间:2024/05/21 01:43

版本一:(较为简单的做法)

先来代码:

#include <stdio.h>/***题目:编写一个程序,该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行数目以及读取的所有其他字符数目。****作者:wsg****时间:2017年8月11日****版本:一***/int main(int argc, char **argv){char ch;int space = 0;//空格数int line = 0; //换行数int otherchars = 0; //其他字符数printf("请输入文本:\n");while(1){scanf("%c", &ch);if(ch == '#') //遇到'#'就结束循环{break;}if(ch == ' ') //遇到空格,space+1{space++;}else if(ch == '\n') //遇到换行,line+1{line++;}else{otherchars++;}}printf("空格数:%d\n", space);printf("换行数:%d\n", line);printf("其他字符数:%d\n", otherchars);return 0;}
注释都很清楚了,来看看运行的结果:


版本二:(运用到了一个并不常见的函数)

代码如下:

#include <stdio.h>    #include <ctype.h>   /***题目:编写一个程序,该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行数目以及读取的所有其他字符数目。****作者:wsg****时间:2017年8月11日****版本:二***//***isgraph(c)函数用于判断字符是否为除空格以外的可打印字符****返回值:若参数c为可打印字符,即其十六进制ASCII码为0x21--0x7e时,返回非零值,否则,返回0;*/int main(int argc, char *argv[])  {      char ch;      int space = 0;  //空格数目    int line = 0;  //换行数目    int otherchar = 0;  //其他字符    int allchars = 0;  //总字符    printf("请输入文本:\n");      while((ch = getchar()) != '#')//连续输入字符,当遇到"#"时结束输入      {          allchars++;  //allchars += 1;亦可        if(ch == '\n')//计算换行符数目              line++;          if(!isgraph(ch) && ch!='\n')//计算空格符数目,!isgraph(c)表示不能打印的字符  这句话的意思是,字符c是不能打印的字符,而且字符c不是回车换行,那么就只有空格了            space++;          if(isgraph(ch) && ch != '\n')//计算出来除空格符、换行符之外的其他字符,isgraph(c)表示可打印的字符            otherchar++;      }      printf("字符的总数= %d\n", allchars);      printf("空格的数目= %d\n", space);      printf("换行符数目= %d\n", line);      printf("其他字符数目为= %d\n", otherchar);    return 0;} 
结果:




阅读全文
0 0