0

The goal behind the following is asking the user for input until an exit string is entered but the preferred execution is not met because this function spams the printf strings and does not take user input more than one time

void test()
{
    int res=0;
    while (res >=0)
    {
        char buffer[1024];
        printf("Enter input: ");
        res = scanf("%[^\n]", buffer);
        printf("\n[%d]you entered: %s\n",res , buffer);
        if (strcmp(buffer, "exit") == 0)
            return ;
    }
}

int main()
{
    test();
    return 0;
}

How to use scanf so that it waits until a user inputs something?

  • 2
    On what character did you tell the input to *stop*, and what do you think happened to that character? Hint: It didn't just magically disappear into the ether. So what do you think happens the *next* time you ask to stop at that point again? Another hint: you're already there. – WhozCraig Sep 05 '22 at 18:35
  • 1
    Reading "[How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)" might help. – Uwe Keim Sep 05 '22 at 18:36
  • 1
    One solution is to put a space at the beginning of the format string to eat the '\n' which remains in the keyboard buffer. `res = scanf(" %[^\n]", buffer);` – CGi03 Sep 05 '22 at 19:18

0 Answers0