Q:终端用键盘输入字符串,以Ctrl+Z组合键表示输入完毕,统计字符串中中空格符、制表符、换行符的个数,并显示统计结果。

思路:

  空格符的ASCII碼是32,制表符的ASCII碼是9,换行符的ASCII碼是10、

  Crtl+Z的组合键输入的字符在计算机中对应的是EOF结束标识符。

 

#include <string.h>
#include <stdio.h>
int main() {
	char c;
	int space=0,table=0,enter=0;
	printf("input a string:\n");
	scanf("%c",&c);
	while(c!=EOF) {
		switch(c) {
			case 32: space++;break;
			case 9:  table++;break;
			case 10: enter++;break;
			default: break;
		}
		scanf("%c",&c);
	}
	printf("the number of space is:\n",space);
	printf("the number of table is:\n",table);
	printf("the number of enter is:\n",enter);
	return 0;
}

擦,居然编译不出来,好尴尬……

考虑了好一会儿,终于编译成功。可是有点小问题,如输入的“Crtl+Z”出现在某个字符之后,就打印不出最后结果。what happened ?

#include <stdio.h>

int main()
{
    int c,m,n,l;
    m=n=l=0;
    /* m代表空格个数,n代表制表符个数,l代表换行符个数 */
    int flag=0;//表示是否遇到换行符 
    while((c = getchar()) != EOF)
    {
        if(c == '\n')
        {
            ++l;
            flag = 1;
            continue;
        }
        else if(flag == 0)
        {
            if(c == ' ')
            {
                ++m;
            }
            if(c == '\t')
            {
                ++n;
            }
        }
    }
    printf("%d\t%d\t%d",m,n,l);
    
    return 0;
}

  从网上找了一个程序,也出现了上述的问题,代码如下:

#include<stdio.h>
int main()
{
	int blanks, tabs, newlines;
	int c;
	int done = 0;
	int lastchar = 0;
	blanks = 0;
	tabs = 0;
	newlines = 0;
	
		while(done == 0)
		{
			c = getchar();
			if(c == ' ')
				++blanks;
			if(c == '\t')
				++tabs;
			if(c == '\n')
				++newlines;
			if(c == EOF)
			{
				/*if(lastchar != '\n')
				{
				++newlines; 
				}*/
				done = 1;
			}
			lastchar = c;
		}
	printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);
	return 0;
}

  

posted on 2017-04-22 21:15  王小东大将军  阅读(208)  评论(0编辑  收藏  举报