This question already has an answer here:
- scanf getchar function is skipped 2 answers
I am trying to make a simple C program for a class and one of the requirements is that I'm required to use scanf
/printf
for all input and output. My question is why is it that my scanf
after the for loop in the main gets skipped and the program just terminates.
Here is my code
#include <stdio.h>
void main() {
int userValue;
int x;
char c;
printf("Enter a number : ");
scanf("%d", &userValue);
printf("The odd prime values are:\n");
for (x = 3; x <= userValue; x = x + 2) {
int a;
a = isPrime(x);
if (a = 1) {
printf("%d is an odd prime\n", x);
}
}
printf("hit anything to terminate...");
scanf("%c", &c);
}
int isPrime(int number) {
int i;
for (i = 2; i < number; i++) {
if (number % i == 0 && i != number)
return 0;
}
return 1;
}
I was able to "fix" it by adding another identical scanf
after the first one, but I would prefer to just use the one.
The new-line character present in
stdin
after the previousint
was entered will not have been consumed by the last call toscanf()
. So the call toscanf()
after thefor
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 thescanf()
after thefor
loop. This will makescanf()
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:this is an assignment (and will always be true):