在C语言中使用'printf'打印变量

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

int main()
{
    int x = 1;

    printf("please make a selection with your keyboard\n");
    sleep(1);
    printf("1.\n");

    char input;
    scanf("%c", &input);
    switch (input) {
        case '1':
            x = x + 1;
            printf(x);
    }
    return(0);
}

我想让一个变量加上自己并将其打印出来,但我似乎无法让我的代码正常工作。

我的输出错误是:

newcode1.c: In function ‘main’:
newcode1.c:20:2: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
In file included from newcode1.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
newcode1.c:20:2: warning: format not a string literal and no format arguments [-Wformat-security]

顺便提一句,你并没有打印一个变量,而是打印了某个变量的[当前] - Basile Starynkevitch
此外,在 scanf 之前最好初始化 input,并测试 scanf 的结果。 - Basile Starynkevitch
2个回答

37

你的 printf 需要一个格式化字符串:

printf("%d\n", x);

这个参考页面详细说明了如何使用printf和相关函数。


这就是我需要做的吗?!?!谢谢,它起作用了。 - Dave

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接