0

I am trying to set up a loop where user can continue entering string. Not sure where i am going wrong (I am new to C programming)

this is the code i have written:

#include <stdio.h>

void main() {
    int repeat;
    char str[30];
    do
    {
        printf("Enter a string:");
        fgets(str, 30, stdin);
        printf("Do you want to continue\n");
        fflush(stdin);
        scanf_s("%d", &repeat);
    } while (repeat==1);
}

This is the output i am getting:

Enter a string:hello
Do you want to continue
1
Enter a string:Do you want to continue
1
Enter a string:Do you want to continue

Thanks in advance.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
plkt
  • 1
  • First mistake `fflush(stdin);` is undefined behavior, probably harmless with the MSVC compiler but certainly wrong according to the standard, also `scanf_s("%d", &repeat);` is not standard either and has special syntax, I don't know exactly how special but I would suggest `scanf("%d", &repeat);` and try a different compiler like *gcc*. Also, `void main()` is wrong, and you must check the return value of `scanf()`. – Iharob Al Asimi Oct 10 '15 at 01:39
  • @ace Even though the standard clearly states that `fflush()`'s behavior is only defined for output streams, Microsof has an implementation for it, and it's often seen in some tutorials online, primarily because of the wrong use of `scanf()` which is also very common. – Iharob Al Asimi Oct 10 '15 at 01:41
  • 1
    Take a look at [this question](http://stackoverflow.com/q/30697465/3488231) and the accepted answer and see if you understand your problem. – user12205 Oct 10 '15 at 01:42
  • If you feel comfortable with `fflush(stdin)`, then add another one after the `scanf()` call. The `\n` (from when you press after typing `1`) is being read by the next `fgets()`. – user12205 Oct 10 '15 at 01:44
  • 1
    @ace I consider that this is a duplicate of that question, nice answer by the way. – Iharob Al Asimi Oct 10 '15 at 01:44

0 Answers0