【问题标题】:Subtracting two chars and adding them to a string [duplicate]减去两个字符并将它们添加到字符串中[重复]
【发布时间】:2013-03-27 06:43:38
【问题描述】:
#include <iostream>
#include <string>

int main() { 
    char s2;
    s2 = '1' - '0';
    std::cout << s2;
    std::cout << std::endl;
    std::cout << '1' - '0';
    std::cin >> s2;
}

产生的输出是:

☺
1

我的问题是,为什么两条线不同?我期望并希望两个结果都是1。根据我的理解,它们应该是相同的,但这显然是错误的,有人可以向我解释一下吗?谢谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    为什么两条线不同?

    第一个表达式 (s2) 的类型是 char。第二个('1' - '0')的类型是int

    这就是为什么即使它们具有相同的数值1,它们的呈现方式也会不同。第一个显示为ASCII 1,而第二个显示为数字1。

    如果您想知道为什么'1' - '0' 给出了int,请参阅Addition of two chars produces int

    【讨论】:

    • 如何让 char (s2) 成为 char '1'
    • @197:添加'0'。或者,如果只是为了输出,请将其转换为int
    • @197 你把它转换成int
    • @197:使用+s2int(s2)static_cast&lt;int&gt;(s2)(int)s2
    • @JonPurdy 好的,我会选择(int)s2
    【解决方案2】:

    s2 是 char,'1'-'0' 是 int。

    所以它输入 char 值 1 表示微笑,1 表示 int 值。

    【讨论】:

      【解决方案3】:

      s2的类型是charstd::cout &lt;&lt; s2会调用std::ostream::operator&lt;&lt;(char)来回显一个ASCII字符1(微笑);

      '1' - '0' 被解释为 int 值,因此将调用 std::ostream::operator&lt;&lt;(int) 并打印整数 1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多