Ivar
Ivar

Reputation: 15

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

Upvotes: 1

Views: 81

Answers (1)

stijn
stijn

Reputation: 35901

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).

Upvotes: 5

Related Questions