显示字母数字和C中的小数位数

时间:2015-01-18 17:42:00

标签: c

我这几个小时以来一直在研究这个简单的代码,我不知道出了什么问题!我需要在标准输入中显示字母数字和小数位数。到目前为止,我有这个:

#include<stdio.h>
#include<ctype.h>
int isalpha(int);
int isdigit (int);
int main()
{
    int c;
    while((c=getchar())!=EOF)
    printf("The number of letters is %d and the number of digits is %d.\n", isalpha(c), isdigit(c));
    return 0;
}

int isalpha(int one)
{
    int ch;
    int i;
    i=0;
    scanf("%d", &ch);
    if(isalpha(ch))
        i++;
    return i;
}

int isdigit(int two)
{
    int a;
    int k;
    k=0;
    scanf("%d", &a);
    if(isdigit(a))
        k++;
    return k;
}

每当我尝试运行它时程序崩溃,我不知道代码的哪一部分是错误的。虽然我在这个领域没有太多经验,所以任何帮助都非常感谢!先感谢您。

2 个答案:

答案 0 :(得分:3)

只需轻轻使用现有的API即可获得如下所示的计数

    int alp = 0;
    int dig = 0;
    while ((c = getchar()) != EOF)
    {
       if (isalpha(c)
           alp++;
       else if (isdigit(c))
           dig++;
    }

    printf("The number of letters is %d and the number of digits is %d.\n", alp,dig);

PS:如果输入中有\n

,请注意刷新换行符

答案 1 :(得分:0)

递归调用的例子

//gcc -O2 count_alpha_num.c -o count_alpha_num
#include <stdio.h>
#include <ctype.h>

void count_alpha_num(FILE *fp, int *alpha, int *num){
    int ch;
    if(EOF==(ch=fgetc(fp)))
        return ;
    if(isalpha(ch))
        ++*alpha;
    else if(isdigit(ch))
        ++*num;
    count_alpha_num(fp, alpha, num);
}

int main(void){
    int a_c = 0, n_c = 0;
    count_alpha_num(stdin, &a_c, &n_c);
    printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
    return 0;
}

相互递归的例子

#include <stdio.h>
#include <ctype.h>

void count_num(int loaded, int ch, int *alpha, int *num);
void count_alpha(int loaded, int ch, int *alpha, int *num){
    if(ch==EOF)
        return ;
    if(isalpha(ch)){
        ++*alpha;
        count_alpha(0, getchar(), alpha, num);
    } else {
        if(loaded)//Already been inspected by 'count_num'
            count_num(0, getchar(), alpha, num);
        else
            count_num(1, ch, alpha, num);
    }
}
void count_num(int loaded, int ch, int *alpha, int *num){
    if(ch==EOF)
        return ;
    if(isdigit(ch)){
        ++*num;
        count_num(0, getchar(), alpha, num);
    } else {
        if(loaded)
            count_alpha(0, getchar(), alpha, num);
        else
            count_alpha(1, ch, alpha, num);
    }
}

int main(void){
    int a_c = 0, n_c = 0;
    count_alpha(0, getchar(), &a_c, &n_c);
    printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
    return 0;
}