C char在编译时显示为int

问题描述 投票:0回答:3

我正在学习C,并且一直在尝试创建一个接受用户输入的程序,并删除其中的任何双重空格,然后再将其打印出来。我们还没有完成数组,所以我需要通过char来做这个char。这是我的代码:

#include <stdio.h>

main()
{
    char c;
    int count;
    count = 0;

    while ((c = getchar()) != '\n')
        if (c == ' ')
            count++;
        if (c != ' ')
            count = 0;
        if (count <= 0)
            printf("%s", c);
}

但是,此代码不起作用。编译器返回错误

:15: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’

有帮助吗?我不知道我做错了什么。

c char int printf compiler-warnings
3个回答
8
投票

使用%c格式说明符打印单个char

printf("%c", c);

%s格式说明符告诉printf期望一个以null结尾的char数组(也就是一个字符串)。

错误消息是指c具有类型int,因为默认提升传递给printf的参数(超出格式字符串)。 This previous answer对默认促销有很好的描述; this previous thread解释了为什么需要进行默认促销的一些原因。


0
投票

您使用的%s用于字符串,并且需要终止NULL字符(\ 0)..

使用%c将打印char char ...


0
投票

你的代码有很多问题

  • 首先,使用%s打印一个char(需要一个char指针,即一个字符串) 在C中,char文字的类型为int,因此无论是否提升,它们都是int。在C ++中,char文字的类型为char,但在推广之后,像其他答案一样,再说它们将是int。一个普通的char变量也将在表达式中提升为int,并在像printf这样的vararg函数中作为int传递。这就是为什么编译器警告你argument 2 has type ‘int’,因为它期待一个char*而你传递它int →您必须使用%c打印字符
  • 你的while循环体只是第一个if块,因为在C块范围是由{}定义的,而不是缩进。因此代码将像这样运行,这与您的意图不同 while ((c = getchar()) != '\n') { if (c == ' ') count++; } if (c != ' ') count = 0; if (count <= 0) printf("%s", c); →您需要将代码块放在一对括号中。并使用else而不是2个单独的ifs使其更具可读性和更快(对于哑编译器) while ((c = getchar()) != '\n') { if (c == ' ') count++; else count = 0; if (count <= 0) printf("%s", c); }
  • main()错了。 C中的正确版本将是 int main(void) int main(int argc, char **argv) What should main() return in C and C++?
  • c必须被宣布为int,因为getchar返回int。见Why must the variable used to hold getchar's return value be declared as int?

一个小问题是,而不是int count; count = 0;,只需在声明int count = 0时初始化变量。或者更好地使用unsigned int,因为计数不能为负

© www.soinside.com 2019 - 2024. All rights reserved.