Issue
So I was assigned to store two 50 digit integers in c language and do math equations using them. the problem for me was to store the input digit by digit in an array. I figured that I can store the input in a char string like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
return 0;
}
But I couldn't use it as a number because it was stored as char and I couldn't copy them digit by digit into another array which was defined as int
after a whole day of searching, I found out that I need to copy my string one by one like this:
#include <stdlib.h>
#include <stdio.h>
int main ()
{
char string_test [50];
scanf("%s", string_test);
int arr[50];
for (int i = 0; i < 50; i++)
{
arr[i] = string_test[i] - '0';
}
return 0;
}
Now my question is why do I need to subtract '0' to get a suitable result?
Solution
The ASCII values for digits 0 - 9 are:
Digit 0 1 2 3 4 5 6 7 8 9
ASCII value 48 49 50 51 52 53 54 55 56 57
So if you have a string representation of an integer, say
char int_str[] = "123456";
and need to convert each char
to its numeric value, subtracting the value for '0'
(48) from each will will result in the values
int_str[0] == '1' ==> '1' - '0' ==> 42 - 41 == 1
int_str[1] == '2' ==> '2' - '0' ==> 43 - 41 == 2
int_str[2] == '3' ==> '3' - '0' ==> 44 - 41 == 3
int_str[3] == '4' ==> '4' - '0' ==> 45 - 41 == 4
int_str[4] == '5' ==> '5' - '0' ==> 46 - 41 == 5
int_str[5] == '6' ==> '6' - '0' ==> 47 - 41 == 6
To get digits 1
2
3
4
5
6
into the integer 123456
requires additional steps:
This example uses the same conversions encapsulated into a function to convert discrete char
digit to int
digit values, then assimilate each discrete int digit value into the composite integer value:
int main(void)
{
char str[] = "123456";
int int_num = str2int(str);
return 0;
}
int str2int(char *str)
{
int sum=0;
while(*str != '\0')
{ //qualify string
if(*str < '0' || *str > '9')
{
printf("Unable to convert it into integer.\n");
return 0;
}
else
{ //assimilate digits into integer
sum = sum*10 + (*str - '0');
str++;
}
}
return sum;
}
Answered By - ryyker Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.