c - "Error: format ‘%d’ 需要类型为 ‘int’ 的参数,但参数 2 的类型为 ‘char *’ "

标签 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);
}

谁能提供一些见解?

最佳答案

您正在 print()first 参数中传递 "%d",因此它(以及编译器,因为您是显然,使用在编译时验证 printf 样式参数的参数)会将第二个参数解释为整数,但您在中传递“%lf”第二个参数。字符串文字在 C 中是 char[],在 C++ 中是 const char[],并且会衰减为 char* >const char* 分别。因此出现错误。

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

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

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

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

关于c - "Error: format ‘%d’ 需要类型为 ‘int’ 的参数,但参数 2 的类型为 ‘char *’ ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488535/

相关文章:

c++ - 如何确定 unsigned char* 的长度?

c - windows linux bash 上的 GCC

C - 使用 signal() 终止进程

c - C中链表的两个结构

c - 一个整数数组和一个指向第一个数组的 int 指针数组,这有意义吗?

c - 数组与两个声明为 C 的数组连接

c - 在c中拆分字符串

c - 所有线程未终止时的 Valgrind 输出

c - 确定 char 是数字还是字母

c - 将值从文本文件传递到数组