scanf Getting Skipped [duplicate]

Solution 1:

The new-line character present in stdin after the previous int was entered will not have been consumed by the last call to scanf(). So the call to scanf() after the for loop consumes the new-line character and continues without the user having to enter anything.

To correct without having to add another scanf() call you could use format specifier " %c" in the scanf() after the for loop. This will make scanf() skip any leading whitespace characters (including new-line). Note it means the user will have to enter something other than a new-line to end the program.

Additionally:

  • check the result of scanf() to ensure it actually assigns a value to the variables passed in:

    /* scanf() returns number of assigments made. */
    if (scanf("%d", &userValue) == 1)
    
  • this is an assignment (and will always be true):

    if (a = 1){ /* Use == for equality check.
                   Note 'a' could be removed entirely and
                   replace with: if (isPrime(x)) */