Reputation: 9
#include<stdio.h>
#include <limits.h>
int main()
{
int value;
int smallest = INT_MAX;
printf("This is a program that finds out the minimum \nof serveral integers you entered.");
printf("Please type in these integers: ");
while(scanf("%d", &value) != EOF)
{
printf(" ");
if(value <= smallest)
{
smallest = value;
printf("%d", smallest); // to trace the while loop
}
}
printf("\nThe smallest integer is: %d", smallest); // this will execute once the program is stopped
return 0;
}
This code can find the smallest integer successfully, but just doesn't print the result from
printf("\nThe smallest integer is: %d", smallest);
.. until I stop the program from my C intepreter. I don't understand why it does not print immediately, since there are no more iterations in the while
loop.
Upvotes: 0
Views: 109
Reputation: 549
You can't use EOF like that , because scanf() returns value 1 after a successful read.scanf() wont return the character it read. I have given solution below, I think it works as you wanted.For any queries comment below.
#include<stdio.h>
#include <limits.h>
int main()
{
int value;
int smallest = INT_MAX;
printf("This is a program that finds out the minimum \nof serveral integers you entered.");
printf("Please type in these integers (Enter any other character to terminate): ");
while(scanf("%d", &value))
{
if(value <= smallest)
{
smallest = value;
printf("smallest till now: %d\n", smallest); // to trace the while loop
}
else
printf("smallest till now: %d\n", smallest); // to trace the while loop
}
printf("\nThe smallest integer is: %d\n", smallest); // this will execute once the program is stopped
return 0;
}
Upvotes: 1
Reputation: 53006
The better end loop condition, is
while (scanf("%d", &value) == 1)
which means while scanf()
is reading values succesfuly.
Read the link to understand why, when using scanf()
it's not natural to wait for EOF
because then the user would have to press a key combination to mark stdin
with EOF
.
That key combination is actually so akward that it's not the same for linux terminals Ctrl+D and for Windows cmd windows Ctrl+Z.
If it does not execute the printf()
statement, it's because you need to flush the stdout
, either add fflush(stdout)
or add a '\n'
at the end of every line, it's more natural to add a newline at the end, although I see that many people add it at the beinning.
Upvotes: 4