AL-zami AL-zami - 1 month ago 6
C Question

Get the number string from a char variable and re-assign it to a integer variable

Here i have a char type variable which holds a number value as string say 21,I want to assign 21 to a integer variable.I did the following thing but it prints -12.why it is printing -12 and how i can get 21 in my int variable?

#include<stdio.h>

int main(){
char character = "21";
int x = (int)character - '0';
printf("%d",x);
}

Answer

Use "sscanf".

int main(){
char *character = "21";
int x = 0;

sscanf(character, "%d", &x);
printf("%d",x);
}