循环整数串给我完全不同的数字?

Kai*_*han 0 c++ string integer loops

我是 C++ 的初学者,所以如果我在这里犯了一个愚蠢的错误,请原谅我。

我想在以下代码中遍历一串整数:

#include <string>

using namespace std;

int main() {
    string str = "12345";
    for (int i : str) {
        cout << i << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但我收到输出:

49
50
51
52
53
Run Code Online (Sandbox Code Playgroud)

我知道如果我使用 char 而不是 int 会得到正常的输出,但是为什么我会收到比应有的多 48 的整数输出?

cig*_*ien 7

当你遍历 a 时,string你会得到 type 的元素char。如果您将 a 转换char为 anint您将获得 的 ASCII 值char,这就是您执行以下操作时发生的情况:

string str = "12345";
for (int i : str) {   // each char is explicitly converted to int 
  cout << i << endl;  // prints the ascii value
}
Run Code Online (Sandbox Code Playgroud)

'0'is48'1'is49等的 ASCII 值解释了您得到的输出。