1

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);
}
3
  • 1
    It is invalid code to put char character = "21";. The data is a string literal which should be assigned to a char array like char character[] = "21"; Commented Oct 21, 2016 at 19:20
  • 1
    Also note that char *character = "21"; is a valid alternative. Commented Oct 21, 2016 at 19:22
  • With the code int x = (int)character - '0'; this would work, but only for a single digit such as char character = '7'; Commented Oct 21, 2016 at 19:23

2 Answers 2

3

Use "sscanf".

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

sscanf(character, "%d", &x);
printf("%d",x);
}
Sign up to request clarification or add additional context in comments.

Comments

0

The proper way to convert from a string to an integer is to use the atoi() or sscanf() functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.