Search code examples
cdebuggingtoupper

Convert to all upper case letter bug in C


I'm a noob so please explain why the following code isn't working? It prints an unnecessary Case 1:. I assume it's not scanning using fgets the first time in the Test Case loop.

Please someone tell me why.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    int i, j, T;
    scanf("%d", &T); //test cases
    char character[100];
    for (j = 1; j <= T; j++) {
        fgets(character, 100, stdin); //input
        for (i = 0; i <= strlen(character); i++) { //function
            if (character[i] >= 91) {
                character[i] = character[i] - 32;
            };
        }
        printf("Case %d: %s", j, character); //result
    }
    return 0;
}

Solution

  • There are multiple issues in your code:

    • you should read the pending newline after getting the number with scanf().
    • you do not check for end of file
    • you include the null terminator in the loop, a simpler test is this:

        for (i = 0; character[i] != '\0'; i++)
      
    • you should use <ctype.h> to convert lower case to upper case or at least use character constants instead of hardcoded ASCII values. The current code would also convert such characters as {, |, }... because they happen to be >= 91.
    • 91 is incorrect anyway. 'a' has value 97 in ASCII.

    Here is a modified version:

    #include <ctype.h>
    #include <stdio.h>
    
    int main() {
        int i, j, T;
    
        if (scanf("%d", &T)) != 1) //test cases
            return 1;
        getchar();  // read pending newline
        char character[100];
        for (j = 0; j < T; j++) {
            if (!fgets(character, sizeof character, stdin)) //input
                break;
            for (i = 0; character[i] != '\0'; i++) { //function
                character[i] = toupper((unsigned char)character[i]);
            }
            printf("Case %d: %s", j + 1, character); //result
        }
        return 0;
    }
    

    ASCII specific version:

    #include <stdio.h>
    
    int main() {
        int i, j, T;
    
        if (scanf("%d", &T)) != 1) //test cases
            return 1;
        getchar();  // read pending newline
        char character[100];
        for (j = 0; j < T; j++) {
            if (!fgets(character, sizeof character, stdin)) //input
                break;
            for (i = 0; character[i] != '\0'; i++) { //function
                if (character[i] >= 'a' && character[i] <= 'z') {
                    character[i] -= 'a' - 'A';
                }
            }
            printf("Case %d: %s", j + 1, character); //result
        }
        return 0;
    }