0

Issue: when the user inputs 'q', the prompt (Number: ) will show up again (which is expected). However, when the user inputs, "q q", the prompt will appear twice ie (Number: Number: ). And when the user inputs "q q q", the prompt will appear 3 times ie (Number: Number: Number: ). is there anyway to fix this code? i am new to programming so i would really appreciate it if you try to explain the problem in layman terms.

int main(void)
{

    char number[17];
    while (true)
    {
        printf("Number: ");
        scanf("%s", number);
        int i;
        char c;
        if (sscanf(number, "%i %c", &i, &c) == 1)
        {
            printf("%i\n", i);
            return 0;
        }
    }
}

2 Answers2

2

i have edited the code according to what u guys have said and it works. Can someone explain to me why this works?

int main(void)
{

    char number[17];
    while (true)
    {
        printf("Number: ");
        fgets(number, 17, stdin);
        int i;
        char c;
        if (sscanf(number, "%i %c", &i, &c) == 1)
        {
            printf("%i\n", i);
            return 0;
        }
    }
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
-1

Another solution is to call fflush(stdin) to clear input buffer.

 if (sscanf(number, "%i %c", &i, &c) == 1)
    {
        printf("%i\n", i);
        return 0;
    }
 else fflush(stdin);