【问题标题】:How do I make my function for counting the amount of Integers in a string work?如何使我的函数用于计算字符串中整数的数量?
【发布时间】:2019-12-17 12:46:40
【问题描述】:

所以,我基本上认为我已经弄清楚了这个小程序 - 我正在尝试制作一个程序,该程序具有查看用户输入的内容并计算用户输入的整数的数量,例如所以:

void finish(int a, char *b, int c);

int main()
{
    int i=0;
    int numb=0;
    char phrase[30];

    printf("This program will count the amount of \nnumbers in an entered phrase.\n");
    printf("Please enter your phrase: ");
    gets(phrase);
    finish(i, phrase, numb);
}

void finish(int a, char *b, int c)
{
    while(b[a]!='\0'){
        if(isdigit(b[a])==1){
                c++;
        }
        a++;
    }
    printf("\nThe phrase you entered has %i numbers",a);
}

从技术上讲,该程序可以工作 - 但它会将输入的所有内容都计算为整数 - 例如,输入 "hello44" 会注册为 6 个数字,而不是只有 2 个。

我制作的一个类似程序在正确注册相同的短语时没有问题,因为只包含 2 个数字,所以我的问题是什么,我该如何在仍然使用函数的同时解决它?

【问题讨论】:

  • 另请注意,isdigit() 不需要在成功时返回1,只是它不是0
  • 关于函数:gets() 该函数已经贬值多年,并从(大约)2009 年完全从 C 语言中删除。建议使用 fgets()(具有不同的参数列表)跨度>
  • 关于:if(isdigit(b[a])==1){ 这是isdigit() 的错误用法。建议:if( isdigit(b[a]) ){
  • 关于:finish(i, phrase, numb);void finish(int a, char *b, int c) main()`中的变量numb只有在传递numb的地址的情况下才能更新。因此这两个语句应该是:finish(i, phrase, &numb);void finish(int a, char *b, int *c)。然后在更新值时,而不是c++; 使用(*c)++; 类似的考虑存在于finish() 的第一个参数

标签: c string function


【解决方案1】:

您的计数变量是 c,但您打印循环变量 a。

【讨论】:

    【解决方案2】:

    在此声明中

    printf("\nThe phrase you entered has %i numbers",a);
    

    输出变量a,而不是变量c。应该有

    printf("\nThe phrase you entered has %i numbers",c);
    

    也是if语句中的条件

    f(isdigit(b[a])==1){
    

    不正确。如果给定字符是数字,则该函数没有必要准确返回1。它可以返回任何非零值。

    第一个和第三个函数参数是多余的。该函数应该只做一件事来计算字符串中的位数。

    函数gets 也不再是标准的C 函数了。这是不安全的。而是使用标准函数fgets

    功能和程序整体可以看如下方式。如下方式

    #include <stdio.h>
    #include <ctype.h>
    
    size_t finish( const char *s )
    {
        size_t n = 0;
    
        for ( ; *s; ++s )
        {
            n += isdigit( ( unsigned char )*s ) != 0;
        }
    
        return n;
    }
    
    int main(void) 
    {
        enum { N = 30 };
        char phrase[N];
    
        printf( "This program will count the amount of\n"
                "numbers in an entered phrase.\n" );
    
        printf( "Please enter your phrase: " );
    
        fgets( phrase, sizeof( phrase ), stdin );
    
        printf( "\nThe phrase you entered has %zu numbers", finish( phrase ) );
    
        return 0;
    }
    

    程序输出可能看起来像

    This program will count the amount of
    numbers in an entered phrase.
    Please enter your phrase: hello44
    The phrase you entered has 2 numbers
    

    【讨论】:

    • 关于; n += isdigit( ( unsigned char )*s ) != 0; 这缺少一组所需的括号。应该是:n += (isdigit( ( unsigned char )*s ) != 0);
    • 我的编译器 gcc 告诉我它缺少一组括号
    • @user3629249 改变编译器!:) 表达式完全正确。
    猜你喜欢
    • 2017-10-06
    • 2015-03-14
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多