Search code examples
cscanf

Why is the scanf() skipped?


#include <stdio.h>

int main() {
    char opt;
    scanf(" %c", &opt);
    switch (opt) {
      case 'A':
        printf("Please Enter a New Name:");
        char name[200];
        scanf("%[^\n]s", name);

        printf("Please Enter a New Code:");
        char code[200];
        scanf("%s", code);

        printf("Please Enter the Number:");
        int number;
        scanf("%d", number);

        printf("%s\n%s\n%d", name, code, number);
        printf("\nPlease press Enter to confirm Creation");
    }
}

Why is the scanf of the name skipped? the output looks like

A
Please Enter a New Name:Please Enter a New Code:

Also when switch() is removed, it works normally. Is the problem on the switch()? It does not have other cases because it is an unfinished code.


Solution

  • As commented by melonduofromage, your first scanf leaves the newline (\n) typed by the user after the A in the input stream. Next scanf("%[^\n]s", name) fails because the first byte from the input stream is a newline, so scanf returns immediately with a return value of 0, which you should not ignore. The program then prompts for the code and scanf skips initial white space, including the pending newline and waits for user input.

    To fix this problem, add a space before the conversion specifier to skip initial white space. You should also limit the number of characters stored into the destination array: specify this number between the % and the [. Note also that the trailing s in "%[^\n]s" is useless: it is not part of the conversion specifier and scanf() will try and match it against the input stream. The correct format is scanf(" %199[^\n]", name) and the return value must be 1 for a successful conversion.

    Also note that there is a missing & in scanf("%d", number): you must pass the address of the destination variable: scanf("%d", &number);

    Here is a modified version:

    #include <stdio.h>
    
    int invalid_input(void) {
        fprintf(stderr, "invalid or missing input\n");
        return 1;
    } 
    
    int main() {
        char opt;
        if (scanf(" %c", &opt) != 1)
            return invalid_input();
    
        switch (opt) {
          case 'A':
            printf("Please Enter a New Name:");
            char name[200];
            if (scanf(" %199[^\n]", name) != 1)
                return invalid_input();
    
            printf("Please Enter a New Code:");
            char code[200];
            if (scanf("%199s", code) != 1)
                return invalid_input();
    
            printf("Please Enter the Number:");
            int number;
            if (scanf("%d", &number) != 1)
                return invalid_input();
    
            printf("%s\n%s\n%d", name, code, number);
            printf("\nPlease press Enter to confirm Creation");
            //...
        }
        return 0;
    }