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.
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.
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);
You can do:
char x[] = "10"; int y = 10;
printf("x + y = %d",atoi(x)+y);
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));
}
Use Below Code..........
#include<conio.h>
#include<stdio.h>
void main()
{
char x=10;
int y=10;
clrscr();
printf("%d",(x+y));
getch();
}
Only for 0 to 9..
if (c >= '0' && c <= '9') {
int v = c - '0';
// safely use v
}