Currently stuck on a uni problem. (Language is C)
The prompt is the following: Create a program that reads a single input character from the terminal checks if the input character is a digit and, if so, converts it into the corresponding integer (use the property of the ASCII values above) prints the value of the integer as an octal number (use the %o specifier in the argument of printf) or the text "the input is not a digit" if the user has entered a non-digit character, e.g. 'q', '$' or 'Z'.
My code is the following:
int valueOfDigit(){
char c;
int i;
c = getchar();
i = c;
if (c <= '9' && c >= '1'){
printf("%o", (int) i);
}
else printf("the input is not a digit\n");
return 0;
}
Im failing the tests as i'm printing the ascii values and not octal. What am i doing wrong? We are not allowed to use any fancy methods either.
CodePudding user response:
Your code does not work, because youre trying to print a char as an int(and by it i mean youre trying to print '6' as 6). The problem is, that the chars are already ints in C(as youve noticed theyre encoded using ASCII standard). To do it simply, and by that i mean not checking anything related to program safety at all, you just have to do the following:
if (c <= '9' && c >= '0'){
printf("%o", (int)(i - '0'));
}
This will print the int number that corresponds to your number in ASCII minus ASCII zero number, which will result in actuall number being printed, for example 6 in ASCII is 54 so minus '0' which is 48 you get 6. Thats the general idea.