Code:
//http://knking.com/books/c2/answers/c13.html
#include <stdio.h>
int main(){
char *digOne[]={"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};
char *digTwo[]={"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", \
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
char num[9];
int x;
printf("Enter a two-digit number: ");
scanf("%s", num); // I enter 23 - it is saved as a string in num
if(num[0]=='0'){ //'0' could be changed 48
sscanf(num, "%d", &x); // saves num as an int inside x
printf("%s", digTwo[x]); // works marvelously
}
else if(num[0]=='1'){ //'1' could also be 49
sscanf(num, "%d", &x); // same as above
printf("%s", digTwo[x]); // works marvelously
}
else{
char both[5];
char ones, tens;
sscanf(num, "%s", both); // this time saves num as a string placed in both
tens = both[0];
printf("tens as int: %d\n", tens); // 2 prints as 50
printf("tens as char: %c\n", tens); // 2 prints as 2 but, I think it is '2'
ones = both[1];
printf("%s", digOne[tens-'2']); //'2' could also be 50
if(digTwo[ones-48]!="zero"){
printf(" %s", digTwo[ones-'0']); //'0' could also be 48
}
}
return 0;
}
I understand why it all works but, I'm sure there was a much cleaner way to solve this problem and the answer to the problem is not provided in the book. I think it is inefficient how I converted things from integer to string, etc. I'm sure there is a better way.