指针警告的整数

时间:2016-11-05 16:27:46

标签: c

我有问题。我从控制台收到2个警告,但我不知道我的代码有什么问题。你看看吗? 程序假设显示至少包含11个字符和4个数字的行

<html>

<head>
  <title>Side Scroll Test</title>
  <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no">

</head>

<body>
  <div id="scroll_cont">
    <div class="scroll_item">Test1</div>
    <div class="scroll_item">Test2</div>
    <div class="scroll_item">Test3</div>
    <div class="scroll_item">Test4</div>
    <div class="scroll_item">Test5</div>
  </div>
</body>

</html>

4 个答案:

答案 0 :(得分:1)

isalpha()isdigit()函数需要int。但是你传递的是char*,即数组line被转换为指向其第一个元素的指针(参见:What is array decaying?)。这就是编译器抱怨的内容。您需要遍历line以查找其中的位数和字母数。

另请注意,如果line有空格,fgets()会在换行符中读取。因此,您需要在计数之前将其修剪掉。

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

int main(void)
{
    char line[200];

    printf("Enter a string: \n");
    while(fgets(line, sizeof(line),stdin))
    {
        int numberAlpha = 0;
        int numberDigit = 0;

        line[strcspn(line, "\n")] = 0; // Remove the trailing newline, if any.

        for (size_t i = 0; line[i]; i++) {
        if(isalpha((unsigned char)line[i])) numberAlpha++;
        else if((unsigned char)isdigit(line[i])) numberDigit++;
        }

        printf("alpha: %d, digits:%d \n", numberAlpha, numberDigit);
    }
    return 0;
}

答案 1 :(得分:1)

isalpha()isdigit()都需要int,而不是char *, as argument

在您的代码中,通过将数组名称作为参数传递,您实际上是在传递char * (array name decays to the pointer to the first element when used as function argument),因此,您将收到警告。

您需要遍历line的各个元素并将它们传递给函数。

那就是说,对于托管环境,int main()只应该int main(void)符合标准。

答案 2 :(得分:1)

isalphaisdigit应该测试char被视为intchar是否可以安全地转换为int )是字母数字或数字字符的编码。您传递了char数组,而不是个人char。你需要测试你得到的每个char字符串,所以你需要一个循环:

for (int i=0; i<strlen(line); i++) {
    if (isalpha(line[i])) numberAlpha++;
    ...
}

最好一次计算长度:

int length = strlen(line);
for (int i=0; i<length; i++) {
    ...
}

您也可以使用指针沿着字符串移动:

for (char *ptr = line; *ptr!=`\0`; ptr++) {
    if (isalpha(*ptr)) ...
    ...
}

答案 3 :(得分:1)

好的,我有这样的事情:

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


int main()
{
    char line[200];

    printf("Enter a string: \n");
    while(fgets(line, sizeof(line),stdin))
    {
        int numberAlpha = 0;
        int numberDigit = 0;
        int i;
        for(i=0; i<strlen(line); i++){
            if(isalpha(line[i])) numberAlpha++;
            else if(isdigit(line[i])) numberDigit++;
        }

        if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
    }

    return 0;
}

现在的问题是,如果可以使它首先接受数据,然后只显示if语句后面的那些行。现在它在输入之后显示行。

相关问题