GCC 编译器警告:格式 ‘%c’需要类型为“char *”的参数,但参数 2 的类型为“int *” [-W格式]

发布于 2025-01-06 17:48:22 字数 1187 浏览 1 评论 0原文

当我尝试编译代码时收到以下警告:

exercise6.c:32:14: warning: format '%c' Expects argument of type 'char *', but argument 2 has type 'int *' [-Wformat]

是什么原因导致此警告以及如何修复它?

/*Write a program that displays the contents of a file at the terminal 20 lines at
a time. At the end of each 20 lines, have the program wait for a character to be
entered from the terminal. If the character is the letter q, the program should
stop the display of the file; any other character should cause the next 20 lines
from the file to be displayed.*/

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int c, i;
    FILE *file;

    if ( (file = fopen ("text", "r")) == NULL )
    printf ("Error opening the file.\n");

    for ( i = 0; i < 20; ) {
        c = getc (file);

        if ( c == EOF ) {
            fclose (file);
            exit (EXIT_SUCCESS);
        }

        putc (c, stdout);

        if ( c == '\n' )
            ++i;

        if ( i == 20 ) {
            scanf ("%c", &c);
            if ( c == 'q' ) {
                fclose (file);
                exit (EXIT_SUCCESS);
            }
            i = 0;
        }
    }
}

I get the following warning when I try to compile the code:

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

What is causing this warning and how do I fix it?

/*Write a program that displays the contents of a file at the terminal 20 lines at
a time. At the end of each 20 lines, have the program wait for a character to be
entered from the terminal. If the character is the letter q, the program should
stop the display of the file; any other character should cause the next 20 lines
from the file to be displayed.*/

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int c, i;
    FILE *file;

    if ( (file = fopen ("text", "r")) == NULL )
    printf ("Error opening the file.\n");

    for ( i = 0; i < 20; ) {
        c = getc (file);

        if ( c == EOF ) {
            fclose (file);
            exit (EXIT_SUCCESS);
        }

        putc (c, stdout);

        if ( c == '\n' )
            ++i;

        if ( i == 20 ) {
            scanf ("%c", &c);
            if ( c == 'q' ) {
                fclose (file);
                exit (EXIT_SUCCESS);
            }
            i = 0;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别把无礼当个性 2025-01-13 17:48:22

定义一个 char ch 并在 scanf 中使用它。

int c, i;
char ch;

/* ... */
scanf ("%c", &ch);

scanf 使用不匹配的参数在技术上是未定义的行为。

Define a char ch and use that in scanf.

int c, i;
char ch;

/* ... */
scanf ("%c", &ch);

Using mismatched arguments for scanf is technically undefined behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文