Search code examples
cscanf

The second scanf to input the age doesn't allow input


Hey I've been trying to resolve this issue I'm having. The second scanf doesn't allow input for an integer. I've checked to make sure everything is correct, but it's still the same thing. Am I missing something? Output stops at "Enter your age at the end of this year: "

int main() {

    int age;
    char usrname;
    
    printf("Hello, Welcome to the birth year calculator!");
    printf("\n\nEnter Your Name: ");
    scanf("%c", &usrname);

    printf("Enter your age at the end of this year: ");
    scanf("%d", &age);

    return 0;
}

Solution

  • First scanf read only 1 char from stdin(cuz usrname is char instead of char array), after then, if stdin is empty -> the second scanf will then wait for input, otherwise the second scanf will be executed automatically after the second prompt printing.

    In your case, I suppose at the first prompt, you have inputted more than 1 chars, in that situation, the second scanf will not wait but run with extra input which was not read by first scanf. e.g if you enter john for the first prompt, then the first scanf takes j, the second scanf takes ohn and try to convert to int.

    To fix this, use char array for the usrname e.g char usrname[128] = {0} or don't input more than 1 char at the first prompt (for the name).

    int main() {
    
        int age;
        char usrname[128] = {0};
        
        printf("Hello, Welcome to the birth year calculator!");
        printf("\n\nEnter Your Name: ");
        scanf("%s", usrname);
    
        printf("Enter your age at the end of this year: ");
        scanf("%d", &age);
    
        return 0;
    }