GCC编译错误:格式'%c'需要类型'char *'的参数,但参数2的类型为'int'[-Wformat]

时间:2012-01-30 21:38:34

标签: c gcc char

好的,我是C的菜鸟,但我认为代码是基本的,直截了当的。该程序适用于大学作业,并且应该具有'isdigit()'功能。这是代码

//by Nyxm
#include <stdio.h>
#include <ctype.h>

main()
{
    char userChar;
    int userNum, randNum;
    srand(clock());
    printf("\nThis program will generate a random number between 0 and 9 for a user to guess.\n");
    /*I changed it from '1 to 10' to '0 to 9' to be able to use the isdigit() function which
    will only let me use a 1 digit character for an argument*/
    printf("Please enter a digit from 0 to 9 as your guess: ");
    scanf("%c", userChar);
    if (isdigit(userChar))
    {
            userNum = userChar - '0';
            randNum = (rand() % 10);
            if (userNum == randNum)
            {
                    printf("Good guess! It was the random number.\n");
            }
            else
            {
                    printf("Sorry, the random number was %d.\n", randNum);
            }
    }
    else
    {
            printf("Sorry, you did not enter a digit between 0 and 9. Please try to run the program again.\$
    }
}

当我尝试编译时,我收到以下错误

week3work1.c: In function ‘main’:
week3work1.c:14:2: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

到底是怎么回事?我迫切需要帮助。任何帮助都可以。我真的很想放弃这个计划。当我的教科书显示“%c”是针对普通的'char'时,为什么说它期望'char *'的论点?我使用的是nano,gcc和Ubuntu,如果这有任何区别的话。

3 个答案:

答案 0 :(得分:14)

对于scanf(),您需要将指针传递给char,否则它无法存储该字符,因为所述char将按值传入。所以你需要&userChar代替。

让我们说userChar在通话前是0。使用您当前的代码,您基本上就是这样做(就实用程序而言):

scanf("%c", 0);

你想要的是这个:

scanf("%c", some-location-to-put-a-char);

哪个是&userChar

man的{​​{1}}页面提到了这一点:

scanf

答案 1 :(得分:1)

scanf("%c", userChar);替换为scanf("%c", &userChar);

答案 2 :(得分:0)

您需要传入指针而不是char的值。

scanf("%c",&userChar);