Reputation: 1637
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?
Upvotes: 1
Views: 296
Reputation: 14619
Use strtol
to convert these character strings into integral types.
It's superior to atoi
because the failure modes are not ambiguous.
Upvotes: 0
Reputation: 4532
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.
Upvotes: 1
Reputation: 9260
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.
Upvotes: 0
Reputation: 10947
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'
Upvotes: 3