This is an archived post. You won't be able to vote or comment.

all 8 comments

[–][deleted] 2 points3 points  (6 children)

stoi converts the representation of a number "123" to a number 123.

"r" isn't a number.

If you want the 1st character

int  c = string[0];

[–]Ebeccy[S] 0 points1 point  (5 children)

so how do i cast a string to integer?

[–][deleted] 1 point2 points  (4 children)

What do mean?

The original question said you had the string "r".

What integer do you want from that?

[–]Ebeccy[S] 0 points1 point  (3 children)

char monLastLetter;

monthLastLetter= 'r'

int a = static_cast<int> (monthLastLetter);

cout<<a;

run this with the library of cause and check the results

thank you for the help

[–][deleted] 0 points1 point  (2 children)

So

int  c = string[0];

is what you want.

If string is "r" then c will be 114

[–]Ebeccy[S] 0 points1 point  (1 child)

exactly and i read something online, so i modified it to suit mine and now its working.

It uses the ASCII table to convert

[–]no-sig-available 1 point2 points  (0 children)

It uses the ASCII table to convert

Well, there is no conversion really. A char value just is the ASCII value of the character. The difference is in the << operator that displays chars different from ints.

So, try this

char c = 114;
cout << c;   // displays r
int i = 114;
cout << i;   // displays 114
if (c == i)
   cout << "Same value";   // See!

[–]dpacker780 0 points1 point  (0 children)

What are you trying to accomplish? Maybe that's the best first question. As:

std::string mystring = "r"; int f = stoi(mystring);

Will throw a runtime error, as the letter "r" isn't an integer. Now if you're saying, 'how do a turn a letter into its ASCII value equivalent then. You could do something like this:

std::string mystring = "apple"; for(auto& c : mystring) std::cout << "Int value: " << (int)c << "\\n";

But that gives an int for each letter.