编写一个程序,该程序读取输入直到遇到#字符,然后报告读取的空格数目。读取的换行符数目以及其他字符数目。
#include <stdio.h>
#include <stdlib.h>
#include<ctype.h>
#include<stdbool.h>
#define STOP '#'
void main()
{
char c;
int n_space =0;
int n_lines =0;
int n_qtchar = 0;
long n_chars = 0l;
printf("请输入文本\n");
while((c=getchar())!=STOP)//连续输入字符,当遇到"#"时结束输入
{
n_chars++;
if(c=='\n')//计算换行符数目
n_lines++;
if(!isgraph(c)&&c!='\n')//计算空格符数目
n_space++;
if(isgraph(c)&&c!='\n')//计算出来空格符、换行符之外的其他字符
n_qtchar++;
}
printf("字符的总数=%d,空格的数目=%d,换行符数目=%d,其他字符数目为=%d\n",n_chars,n_space,n_lines,n_qtchar);
}
程序使用isgraph()函数来辨别空格,该函数在头文件ctype.h中,
if(isgraph(c)&&c!='\n')//计算出来空格符、换行符之外的其他字符
这句要注意使用c!='\n';不然会计算出不正确的空格数,因为它会把换行符也 跟着计算进去。