1

I want to retrieve a numeric value from a character type variable.

char x = '10';
int y = 10;
printf("x + y = %d",(int)x+y);

I expect 20 as the result.

MSU_Bulldog
  • 3,501
  • 5
  • 37
  • 73
King Rayhan
  • 2,287
  • 3
  • 19
  • 23
  • 1
    What have you tried? There are built in tools, but it is a great programming learning exercise to write your own string to numeric converter. – john elemans Nov 30 '15 at 18:14

5 Answers5

3

printf("x + y = %d",(int)x+y);

Casting char to int doesn't convert it to a number, but rather gives you the integer value corresponding to the character that it's representing (typically ASCII or something compatible, but the C standard doesn't specify that). Here you're using a multi character literal (normally anything enclosed in single quotes should be just one character), to make matters worse; this is implementation defined as well. If you want to store more than a single digit, you will need a string:

const char* x = "10".

You can then convert it to an integer using atoi or strtol. atoi is easier to use, but provides no way of checking whether or not the string contains a valid number.

Example:

const char* x = "10"; int y = 10;
printf("x + y = %d", atoi(x) + y);
Community
  • 1
  • 1
user4520
  • 3,401
  • 1
  • 27
  • 50
0

You can do:

char x[] = "10"; int y = 10;
printf("x + y = %d",atoi(x)+y);
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

If you have a C library, use atoi(char *x), secondly characters cannot hold 2 characters, for that you need an array or pointer. Here's the code that you may need:

int main(){
        char *c = "10";
        int i = atoi(c);
        int j = 10;
        printf("i + j=%d",(i + j));
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Zach S
  • 86
  • 1
  • 7
0

Use Below Code..........

#include<conio.h>
#include<stdio.h>
void main()
{
    char x=10;
    int y=10;
    clrscr();

    printf("%d",(x+y));
    getch();
}
0

Only for 0 to 9..

if (c >= '0' && c <= '9') {
    int v = c - '0';
    // safely use v
}