简体   繁体   中英

String.at() returning funky numbers

when I am trying to run this snippet of code I am getting some malfunctions I have not been able to pinpoint the cause of. The first two "cout" lines display the numbers 7 and 3, however, the last "cout" line displays numbers ranging from 50-60 usually (At the moment when I run it I get 55 and 51, which seems to somehow correlate a bit with the numbers I am trying to read). As far as I can tell from some googling and the books I have at hand this should be valid, but there's obviously something I am missing. Thank you for your time.

#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;
}

the program functions correctly: text.at() returns a char , which you implicitly convert to an int . Then you print the value of that int, which are respectively 55 for "7" and 51 for "3" (look here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM