scanf
does not return the value entered. It returns the number of inputs matched. So your check for 42 is incorrect. It will return 1 if an integer was assigned to i
, or 0 if there was invalid input. If you want to exit the loop when the user enters 42, you should explicitly test if (i == 42)
.
As simonc mentioned, The reason you're not getting any output is because printf("%d",i);
is not printing a newline "\n"
after the number, and the standard out (stdout
) stream is line-buffered. That means the standard library is going to continue to buffer up your printf
s until a newline is encountered. At this point the buffer will be flushed to the console.
The solution is to add the newline (which is probably what you desire anyway): printf("%d\n",i);
Alternatively, you could call fflush(stdout)
to tell the std library to flush the buffered content to the console immediately. Or, writing to stderr
will output immediately, because it is unbuffered.
This should demonstrate:
#include <stdio.h>
int main()
{
int i;
while(1) {
fprintf(stderr, "Enter a number (or 42 to quit): ");
if((scanf("%d",&i)) != 1) {
fprintf(stderr, "Invalid input.\n");
continue;
}
if (i==42)
break;
printf("Number provided: %d\n", i);
}
return 0;
}
Output:
$ ./a.exe
Enter a number (or 42 to quit): 17
Number provided: 17
Enter a number (or 42 to quit): 42
$