1

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);
    }
}
4
  • If you check the return value from scanf, you'll see that it's not reading anything, which could be a good clue. Commented Sep 29, 2020 at 23:18
  • Note that you almost certainly meant "%[^\n]" instead of "%[^\n]s", unless you really want to match a literal s in the input. Commented Sep 29, 2020 at 23:24
  • Does this answer your question? Read a string as an input using scanf Commented Sep 29, 2020 at 23:28
  • This may also be relevant: stackoverflow.com/questions/42265038/… Commented Sep 29, 2020 at 23:37

2 Answers 2

1

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);
           ^
           |
    
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.