Function of the code: The function of my code is pretty simple. It converts a phone number with numbers into a phone number.
#include <stdio.h>
main(){
char num;
printf("Please enter a phone number with letters to be converted into a phone number: \n");
while ((num = getchar()) != '\n') {
switch(num){
case 'A': case 'B': case 'C': printf("2"); break;
case 'D': case 'E': case 'F': printf("3"); break;
case 'G': case 'H': case 'I': printf("4"); break;
case 'J': case 'K': case 'L': printf("5"); break;
case 'M': case 'N': case 'O': printf("6"); break;
case 'P': case 'R': case 'S': printf("7"); break;
case 'T': case 'U': case 'V': printf("8"); break;
case 'W': case 'X': case 'Y': printf("9"); break;
default: putchar(num);
}
return 0;
}
}
The problem is that the getchar()
is taking one value and changing that number/letter only when I want it to change the whole thing.
Things I have done: I found someone else code who did this already, copied it, changed it a bit (removed toupper
function), stacked the cases
side by side and it didn't work for some reason. Is it because of the placement of the switch statement? But I don't think it is because of that because it ends after printing one value.
What I want it to do:
Enter phone number: 1-800-COL-LECT
1-800-265-5328
What it does:
Enter phone number: 1-800-COL-LECT
1
Enter phone number: 5-469-COL-LECT
5
The problem in the code is that return 0;
is inside of your while
loop. What you need to do is move the return 0;
outside of the loop and it will fix it.
#include <stdio.h>
main(){
char num;
printf("Please enter a phone number with letters to be converted into a phone number: \n");
while ((num = getchar()) != '\n') {
switch(num){
case 'A': case 'B': case 'C': printf("2"); break;
case 'D': case 'E': case 'F': printf("3"); break;
case 'G': case 'H': case 'I': printf("4"); break;
case 'J': case 'K': case 'L': printf("5"); break;
case 'M': case 'N': case 'O': printf("6"); break;
case 'P': case 'R': case 'S': printf("7"); break;
case 'T': case 'U': case 'V': printf("8"); break;
case 'W': case 'X': case 'Y': printf("9"); break;
default: putchar(num);
}
}
return 0;
}
Originally founded by @kaylum