Why does program terminate without taking input?

Viewed 150

This is sample of my program:

#include <stdio.h>
void sum();
int main()
{
    char choice[4];
    do
    {
        sum();
        printf("\nDo You want to restart the program: yes or no:\n");
        fgets(choice, 4, stdin); //error point
    } while (choice[0] == 'y' || choice[0] == 'Y');
    printf("\nThanking You");
    return 0;
}
void sum()
{
    int a = 3, b = 4;
    printf("sum of two number is %d", a + b);
}

In this program, only in the 1st iteration of while does it ask for input in choice and, on the next iteration the program auto terminates by taking any value in choice.

Following is the result after execution of code:

sum of two number is 7
Do You want to restart the program: yes or no:
yes
sum of two number is 7
Do You want to restart the program: yes or no:

Thanking You
[Program finished]

I am unable to understand that it takes input in choice while I haven't used scanf() (which leaves the new line character in the buffer). It may be it takes input from buffer that may be whitespace or other characters, but I don't know from where it came?

2 Answers

Your program is leaving a newline in the input buffer after the first prompt because there's not enough room for it in the buffer.

On the first call to fgets you give the string "yes" followed by a newline. The buffer has size 4 and you pass that size to fgets so it reads at most that many characters-1 to account for the terminating null byte. So there is still a newline left in the buffer.

That newline gets read immediately the next time fgets is called.

You should enlarge your buffer to handle more characters.

Your choice array is not large enough to hold all the input from the first loop. The second argument to the fgets function (4) tells it to read at most 3 characters (and it then appends a nul-terminator to the input). So, it leaves the newline character in the input stream, and that is read in the second loop (by itself).

Just increase your choice array size and the input limit to 5 (or more):

#include <stdio.h>
void sum();
int main()
{
    char choice[5]; // Increase space for newline and nul
    do {
        sum();
        printf("\nDo You want to restart the program: yes or no:\n");
        fgets(choice, 5, stdin); // Inputs 'y', 'e', 's' and newline (4 chars) and appends a nul.
    } while (choice[0] == 'y' || choice[0] == 'Y');
    printf("\nThanking You");
    return 0;
}
void sum()
{
    int a = 3, b = 4;
    printf("sum of two number is %d", a + b);
}

From fgets - cppreference (bolding mine):

Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Parsing stops if a newline character is found, in which case str will contain that newline character, or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position immediately after the last character written to str.

Related