【问题标题】:How to make a function call with an array of characters in C如何在C中使用字符数组进行函数调用
【发布时间】:2016-07-03 10:36:18
【问题描述】:

这是一个显示字符串中单词数量的程序。 我设法进行了函数调用,但给了我“参数列表语法错误”的错误。 任何答案都会有很大帮助。

    #include<stdio.h>
    int wordCount(char str[],int b);
    main()
    {
        char str[100];
        int b, d;
        clrscr();  // clear the screen every compile and build

        printf("Write your message: ");
        gets(str);   //reads the str[] which the user input
        b = strlen(str);  // run without the <string.h>

        d = wordCount(str,b);

        printf("No. of words: %d", d);

    getch();
    }

    int count(str[],b) // Where the error points out
    {
        int i=0,word=0;

        for (i = 0; i < b; i++)
        {
            if (str[i] != ' ' && str[i] != '\t')
            {
                word++;
                while (str[i] != ' ' && str[i] != '\t')
                {
                    i++;
                }
            }
        }
        return word;
    }

【问题讨论】:

标签: c arrays string count character


【解决方案1】:

您必须在函数定义中指定参数的类型:

int count(str[],b){ ...

应该变成

int wordCount(char str[],int b){ ...

就像在你的函数声明中一样。

另外,你必须指定main()的返回类型 -> int main()

另外,你必须#include &lt;string.h&gt; 才能使用strlen()

【讨论】:

【解决方案2】:

这是我在您的代码中所做的更改,现在可以使用了

#include<stdio.h>
int wordCount(char str[],int b);
main()
{
    char str[100];
    int b, d;
    clrscr();

    printf("Write your message: ");
    gets(str);
    b = strlen(str);
    d = wordCount(str,b);

    printf("No. of words: %d", d);

getch();
}

int wordCount(char str[],int b)
{
    int i=0,word=0;

    for (i = 0; i < b; i++)
    {
        if (str[i] != ' ' && str[i] != '\t')
        {
            word++;
            while (str[i] != ' ' && str[i] != '\t')
            {
                i++;
            }
        }
    }
    return word;
}

在您的代码中,您没有输入您声明的正确函数名称,也没有给出参数类型,这就是它给您错误的原因。

【讨论】:

  • 对于str[] == "abc",while (str[i] != ' ' &amp;&amp; str[i] != '\t') { i++; } 没有明确的理由停止循环。
猜你喜欢
  • 2016-06-27
  • 2013-10-23
  • 1970-01-01
  • 2021-12-13
  • 2023-02-13
  • 1970-01-01
  • 2022-11-20
  • 2020-04-30
  • 1970-01-01
相关资源
最近更新 更多