gpt4 book ai didi

c - GCC 编译错误 : format ‘%c’ expects argument of type ‘char *’ , 但参数 2 的类型为 ‘int’ [-Wformat]

转载 作者:太空狗 更新时间:2023-10-29 17:16:58 25 4
gpt4 key购买 nike

好吧,我是 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”用于常规 ole 'char' 时,为什么它说它期望 'char *' 的参数?如果有任何不同,我正在使用 nano、gcc 和 Ubuntu。

最佳答案

对于scanf(),你需要传递一个指向char的指针,否则它没有办法存储字符,因为 char 将按值传递。所以你需要 &userChar 来代替。

假设 userChar 在调用之前是 0。使用您当前的代码,您基本上是这样做的(就实用程序而言):

scanf("%c", 0);

你要的是这个:

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

这是 &userChar

scanfman 页面提到了这一点:

   c      Matches  a  sequence  of characters whose length is specified by
the maximum field width (default 1); the next pointer must be a
pointer to char, and there must be enough room for all the char‐
acters (no terminating null byte is added). The usual skip of
leading white space is suppressed. To skip white space first,
use an explicit space in the format.

关于c - GCC 编译错误 : format ‘%c’ expects argument of type ‘char *’ , 但参数 2 的类型为 ‘int’ [-Wformat],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9071140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com