【问题标题】:Format %c expects argument of type char* but has int格式 %c 需要 char* 类型的参数,但具有 int
【发布时间】:2020-07-27 23:15:58
【问题描述】:

所以我知道我已经定义了字符。但是有些东西让编译器很烦。

        char direction;
        int exit, firstLine, length;
        firstLine = 0, exit = 0;

        /* Boolean for the whether size has been read. */
        while (((fgets(line, sizeof(line), boardFile)) != NULL) || exit == 1)
        { 
            if (firstLine == 0)                                     /* Easy way of handling reading width/height. */
            {
                /* Split for size and width. */
                sscanf(line, "%d,%d", widthPtr, heightPtr);             /* Store width and height inside width/height. */
                firstLine++;
                if (VALIDSIZE(*widthPtr))
                {
                    if (!(VALIDSIZE(*heightPtr)))
                    {
                        printf("%d is an invalid Height. Must be between 1 and 12 (Inclusive).", *heightPtr);
                        exit = 1;
                    }
                }
                else
                {
                    printf("%d is an invalid Width. Must be between 1 and 12 (Inclusive).", *widthPtr);
                    exit = 1;
                }
            }
            else
            {
                Ship* newShip;
                sscanf(line, "%s %c %d %[^\n]", location, direction, &length, name);    /* Parse into vars. */
                newShip = createStruct(location, direction, length, name);              /* Need a createStruct method so it doesn't store the same Struct in the same memory location. */
                insertLast(list, newShip);                                              /* Add to the list of structs. */
            }   

我遇到的错误

format %c expects argument of type char* but argument has type int.

我正在尝试读取这个字符串

D4 E 3 NullByte Sub

它作为一个 char* 工作,但我需要它是一个 char,因为它只是一个字符。

E 是我要扫描到 char 中的内容,而 scanf 是引发错误的内容。

任何帮助都非常感谢

【问题讨论】:

    标签: c parsing char scanf


    【解决方案1】:

    虽然这不是我可以编译和测试的 MCVE,但您可能需要编写

    sscanf(line, "%s %c %d %[^\n]", location, &direction, &length, name);
    

    也就是说,%c 对应的参数需要是指向char 的指针,就像%d 对应的参数需要是指向int 的指针一样。

    您收到一条令人困惑的消息,其中提到 int,因为 C 的一个历史怪癖:可变参数函数参数(格式字符串后的 ...)仍然使用 ANSI C 之前的旧规则进行提升。所以,@ 987654328@ 扩大到int。这是为了向后兼容 70 年代和 80 年代的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2014-04-23
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多