Carson147
Carson147

Reputation: 29

C while loop does not stop running once input is made

I am trying to create a program that repeatedly asks the user for input. However, in this case, the program just keeps printing "Enter your input" until it crashes after I enter something for the first time.

#include <stdio.h>

int main() {

    while (1) {
        char input[100];

        printf("Enter a input: ");
        scanf("%[^\n]s", input);
    }
}

Upvotes: 1

Views: 513

Answers (2)

anastaciu
anastaciu

Reputation: 23792

In:

scanf("%[^\n]s", input);

There are 2 problems:

  1. The s is not part of that specific specifier, it should be only %[^\n].

  2. That specifier leaves the \n newline character in the input buffer.

    Your cycle will enter an infinite loop because there is always something to read there, but it's something that must not be parsed and should remain in the buffer.

    A simple way to get rid of it is to place a space before the specifier:

    scanf(" %[^\n]", input);
           ^
           |
    

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595557

You are asking scanf() to read everything up to, but not including, the line break that ends the user's input.

So, the line break stays in the input buffer. Then on subsequent calls to scanf(), the line break is still not read from the input buffer, preventing scanf() from reading any new input.

You need to read that line break from the input buffer so that a subsequent call to scanf() can read the user's next input.

Upvotes: 1

Related Questions