Question

Really confused if my program is behaving the way it's supposed to. this isn't homework, just a fun march madness predictor program I'm writing.

    char buffer[20];
    char team1_name[20];    // 18 chars + new line + null
    char team2_name[20];

    printf("Who is team 1?\n");
    fgets(buffer, sizeof(buffer), stdin);
    strncpy(team1_name, buffer, sizeof(team1_name));
    team1_name[strlen(team1_name) - 1] = '\0';

    printf("\nWho is team 2?\n");
    fgets(buffer, sizeof(buffer), stdin);
    strncpy(team2_name, buffer, sizeof(team2_name));
    team2_name[strlen(team2_name) - 1] = '\0';

    printf("\nEnter %s's info:\n", team1_name);

Out of curiosity I enter a team name greater than 20 characters and it completely skips over the second print statement. am I protecting against buffer overflow? is it up to the user to not put in something huge? Do I need flush statements?

This is the output:

    Who is team 1?
    wjefowiejfwoiejfweoifjweoifjweofijweoifj

    Who is team 2?

    Enter wjefowiejfwoiejfwe's info:
    Wins in last 12:

    Losses in last 12:

    Points per game:
Was it helpful?

Solution

The problem is that, since your input is truncated in the first fgets (you have more than 20 chars), then the second fgets will read the end of the FIRST input string from stdin.

Display "team2_name" value to see it (it contains chars after the 20 first chars in team1_name).

Oops, sorry, the following comment was wrong. Forget about it : And yes, fgets MUST use sizeof(buffer)-1, because this argument is the max number of chars read. So if you read sizeof(buffer) chars, you will need sizeof(buffer)+1 chars to store them (including trailing '\0')

OTHER TIPS

You read 20 chars out of stdin, but the rest of the input still remains in the stream. The next fgets reads those remaining chars, so Team1 is called wjefowiejfwoiejfwe and Team2 oifjweofijweoifj. Print Team2's name as well and you will see this is true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top