1

I got a set of characters as input using scanf which is actually like this "1854?156X".

(using scanf("%c",&input[i]) , input is an array of 10 characters);

In further processing of code I want to multiply the (first digit *10) & (second digit *9) and so on.

So, while multiplying it is taking the ASCII value of 1 which is actually (49 *10), instead of (1*10).

input[i]*counter;

where counter is

int counter=10;

How can I convert the char array to integer array where the exact digit should be multiplied instead of ascii value of that character?

3
  • 1
    Not necessarily portable to all other character sets, but in ASCII, at least, you can use c - '0' to convert c to its integer equivalent, provided you've verified (by isdigit() or similar), that c is, in fact, a digit. Commented Aug 17, 2012 at 14:58
  • i have verified the inputs with Isdigit Commented Aug 17, 2012 at 15:00
  • The reason I mentioned verifying a characters digit-ness is your sample input included '?' and 'X', which are generally not considered digits... The point is that input validation is a good thing... Commented Aug 17, 2012 at 15:09

4 Answers 4

3

If you know ahead of time that you value is ascii then simply subtract the value of '0' from it. E.g. '9' - '0' = 9'

Sign up to request clarification or add additional context in comments.

Comments

1

Definitely use atoi(). It spares you a lot of manual character checking.

int input_val = atoi(input);
int temp = input_val;

while(temp)
{
  int digit = temp % 10;
  temp /= 10;
}

This gives you each digit from right to left in "digit". You can construct your number using addition and multiplying by powers of 10.

Comments

0

Take the ascii value and subtract 48.

That is input[i] - '0'

...or rather use atoi(). It returns zero if it fails on conversion, so you don't need to bother with '?' and such characters in your array while you traverse it.

Comments

0

Use strtol to convert these character strings into integral types.

It's superior to atoi because the failure modes are not ambiguous.

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.