“错误:格式为'%d'的参数应为'int'类型,而参数2的类型为'char *'”

时间:2018-09-24 23:16:43

标签: c

当我尝试编译此代码时,我一直收到此错误:

#include <stdio.h>

int main(void)
{
    int    userInt;
    int    x;
    double userDouble;
    char   userChar;
    char   userString[20];

    printf("%d", "%lf", "%c", "%s", userInt, userDouble, userChar, userString);
}

谁能提供一些见识?

1 个答案:

答案 0 :(得分:4)

您正在"%d" first 参数中传递print(),所以(和编译器一样,因为您显然在编译时使用了一个验证printf样式参数的参数) -time)会将 second 参数解释为整数,但是您在 second 参数中传递了"%lf"。字符串文字在C中是char[],在C ++中是const char[],并且将分别衰减为char*const char*。因此是错误。

您只需要将所有格式说明符放在 first 参数中,例如:

printf("%d %lf %c %s", userInt, userDouble, userChar, userString);

或者,如果您真的想在输出中用引号和逗号分隔值:

printf("\"%d\", \"%lf\", \"%c\", \"%s\"", userInt, userDouble, userChar, userString);
相关问题