解释当整数作为输入时输出

Explain the output when a integer is given as input

本文关键字:输入 输出 整数 解释      更新时间:2023-10-16

-当整数是输入时解释输出

-

为什么 -47 在输入为 5 时递增该值

#include <iostream>
using namespace std;
int main() {
        string s;
        cin>>s;
        cout<<(*s.begin())-47;
    }
    return 0;
    }

在 ASCII 字符 2 中,代码为 50。所以 50 - 47 将导致 3。因此,如果在语句中

   cin>>s;

你被 2

然后在语句中

    cout<<(*s.begin())-47;

等效于 '2' - 47 的表达式 *s.begin()-47 由于整数提升而转换为类型 int 并且等于 3 ( '2' - 47 => 50 - 47 == 3)。

考虑到调用s.begin()返回指向字符串的第一个字符的迭代器,*s.begin()生成字符本身。