0

So I have a string like this: "MULTR12"

I want to get '1' and '2' as two seperate integers. How do I go about doing that? Before, I had it simply as:

char *string = "MULTR12";
val = string[5];

But I get a really weird value for val instead of 1, like I want. Can anyone help? Thanks!

user2253332
  • 797
  • 3
  • 12
  • 21

4 Answers4

5

This is how you convert a char to int ..

int x = string[5] - '0';

Here's some explanation.. Every character is represented as an ASCII character in memory, A will be 65 and simliar. This also applies to numbers, so 0 in ASCII is 48, 1 is 49 etc.

Now, when we subtract 0 from any number's ASCII representation. Let's say the number is 5, this is what we are actually doing..

int x = 53 - 48

which gives us 5 as an integer. In other words, we are calculating the displacement of that numbers ASCII representation from 0's ASCII representation.

vidit
  • 6,293
  • 3
  • 32
  • 50
2

A bit hackish but try

val = string[5] - '0';

Shamelessly stolen from here

What you are trying to do above, is basically take the ASCII representation of the char '1' and convert it to an int, yielding 49. (probably not what you expected)

Community
  • 1
  • 1
Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45
  • "basically take the ASCII representation of the char `'1'`" - not necessarily ASCII. –  Apr 21 '13 at 05:35
  • True, but I was looking for a quick way to summarise. Isn't ASCII in the world of Unicode nowadays :P – Sinkingpoint Apr 21 '13 at 05:39
1

You can do something like this:

int num = string[ 5 ] - '0';
Man Vs Code
  • 1,058
  • 10
  • 14
0

Actually you are getting a weird value because you are trying to change the value of a string that is fixed. First take a new array as char str[]="Multr12"; Now you can access str[5]...try this