String.at() 返回时髦的数字

String.at() returning funky numbers

本文关键字:数字 返回 at String      更新时间:2023-10-16

当我尝试运行这段代码时,我遇到了一些故障,我无法查明原因。前两个"cout"行显示数字 7 和 3,但是,最后一个"cout"行通常显示 50-60 范围内的数字(在我运行它的那一刻,我得到 55 和 51,这似乎以某种方式与我试图读取的数字相关联)。据我从一些谷歌搜索和我手头的书中可以看出,这应该是有效的,但显然我错过了一些东西。谢谢你的时间。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string text = "73";
    int one=0, two=0;
    cout << text.at(0) << endl;
    cout << text.at(1) << endl;
    one = text.at(0);
    two = text.at(1);
    cout << one << endl << two << endl;
    return 0;
}

程序运行正常:text.at()返回一个char,你隐式地将其转换为int。然后打印该 int 的值,分别为 "7" 的 55 和"3" 的 51(看这里)。