I’m trying to solve the problem here but I don’t know why my code isn’t working. Any help is appreciated. EDIT: Edited to make correction mentioned below, but there is still an extra “15” (in bold) on the second line of the output and I don’t understand where it is coming from.
My output is
18662658515
555227215
#include <stdlib.h>
#include <stdio.h>
int main(void){
int n;
int j;
scanf("%d\n", &n);
int i = 0;
char mystr[15];
for(;i<n;i++){
fgets(mystr,15,stdin);
for(j=0;j<15;j++){
if(isdigit(mystr[j])){
printf("%c", mystr[j]);
continue;
}
if ('A' <= mystr[j] && mystr[j] <= 'C')
printf("2");
if ('D' <= mystr[j] && mystr[j] <= 'F')
printf("3");
if ('G' <= mystr[j] && mystr[j] <= 'I')
printf("4");
if ('J' <= mystr[j] && mystr[j] <= 'L')
printf("5");
if ('M' <= mystr[j] && mystr[j] <= 'O')
printf("6");
if ('P' <= mystr[j] && mystr[j] <= 'S')
printf("7");
if ('T' <= mystr[j] && mystr[j] <= 'V')
printf("8");
if ('W' <= mystr[j] && mystr[j] <= 'Z')
printf("9");
}
printf("\n");
}
}
The problem is that you’re iterating over all 15 characters in the input string, regardless of the length of the input. The first test case has 11 characters, but the second case has only 8. In the second iteration, you’re accidentally processing the last two characters from the first input, which were
15.To fix it, just stop your iteration when you hit the NUL character 0, which terminates the string by changing this line
to