Home > database >  The second scanf to input the age doesn't allow input
The second scanf to input the age doesn't allow input

Time:09-22

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;
}

CodePudding user response:

The problem is the following two lines:

printf("\n\nEnter Your Name: ");
scanf("%c", &usrname);

You are telling the user to enter something that consists of more than a single character, but you are only extracting a single character from the input stream and writing it to usrname.

For example, if you enter Michael, then you will extract the M from the input stream, leaving ichael on the stream.

Afterwards, you will execute the line

scanf("%d", &age);

which will attempt to convert what is left on the input stream to an integer. However, this will fail, because it is not possible to convert ichael to an integer.

It is generally not recommended to use scanf for line-based user input. This is because scanf does not behave in an intuitive manner. For example, as demonstrated above, it does not always read one line of input in one function call, which can cause trouble, as it did with you.

For this reason, it is generally recommended to use the function fgets instead, which will always read exactly one line of input, if possible. After reading one line of input as a string, you can attempt to convert it to an integer, for example using the function strtol.

Note that fgets will also write the newline character at the end of the line to the string, so you will probably want to remove it. You may want to read this question on how to do that:

Removing trailing newline character from fgets() input

Here is an example:

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

int main()
{
    char usrname[200];
    char line[200];
    int age;
    
    printf("Hello, Welcome to the birth year calculator!");

    printf("\n\nEnter Your Name: ");
    fgets( usrname, sizeof usrname, stdin );

    //remove newline character
    usrname[strcspn(usrname,"\n")] = '\0';

    printf("Enter your age at the end of this year: ");
    fgets( line, sizeof line, stdin );
    age = strtol( line, NULL, 10 );

    return 0;
}

CodePudding user response:

Other than the odd choice of char usrname it works for me. If you type more than 1 letter before enter in it will cause the 2nd scanf() to fail which you will see with error checking. If you don't want any input for the first prompt to bleed into the 2nd then you need to flush the input stream between. Minimized scope of variables:

#include <stdio.h>

int main() {
    printf("\n\nEnter Your Name: ");
    char usrname;
    if(scanf("%c", &usrname) != 1) {
        printf("usrname failed\n");
        return 1;
    }
    printf("Enter your age at the end of this year: ");
    int age;
    if(scanf("%d", &age) != 1) {
        printf("age failed\n");
        return 1;
    }
    printf("name=%c, age=%d\n", usrname, age);
    return 0;
}

You probably want to use a string instead a char for the usrname. If your user name contains space then you are better off reading a line with fgets() instead of scanf(). Also changed age to an unsigned.

#include <stdio.h>
#define TADMAN_IS_NOT_STINGY 254
#define str(s) str2(s)
#define str2(s) #s

int main() {
    printf("\n\nEnter Your Name: ");
    char usrname[TADMAN_IS_NOT_STINGY 1];
    if(scanf("%" str(TADMAN_IS_NOT_STINGY) "s", usrname) != 1) {
        printf("usrname failed\n");
        return 1;
    }
    printf("Enter your age at the end of this year: ");
    unsigned age;
    if(scanf("%u", &age) != 1) {
        printf("usrname failed\n");
        return 1;
    }
    printf("name=%s, age=%u\n", usrname, age);
    return 0;
}

CodePudding user response:

Before DV'ing this C answer, read the comments below.


This is what I did and it seemed to work just fine.

I created a class, not sure if that's even necessary

class Person {
    std::string userName;
    int age;
}

main() {
    Person shalofty;
    std::cout << "Enter name and age" << std::endl;
    std::cin >> shalofty.userName;
    std::cin >> shalofty.age;
}

CodePudding user response:

Different people see different priorities and offer different advice. Here, in commented code, is another version close to your original version but embellished

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

int main()
{
    char usrname[200] = { 0 }; // ALWAYS initialise variables
    
    printf("Hello, Welcome to the birth year calculator!");

    printf("\n\nEnter Your Name: ");

    if( scanf( "%[^\n]", usrname ) != 1 ) { // test return codes
        fprintf( stderr, "Scanf failed\n" );
        exit( EXIT_FAILURE );
    }

    // remove trailing '\n' from the name entered
    usrname[ strcspn( usrname, "\n" ) ] = '\0';

    int usrage = 0; // define and initialise variables close to use
    printf("Enter your age at the end of this year: ");

    if( scanf( "%d", &usrage ) != 1 ) { // test return codes
        fprintf( stderr, "Scanf failed\n" );
        exit( EXIT_FAILURE );
    }

    // do something with the user's input
    printf( "Hello %s, who will be %d years old at year's end\n", usrname, usrage );

    return 0;
}

Output

Hello, Welcome to the birth year calculator!

Enter Your Name: Foo Bar
Enter your age at the end of this year: 42
Hello Foo Bar, who will be 42 years old at the end of this year

CodePudding user response:

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;
}
  • Related