#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#ifndef EOF
#define EOF (-1)
#endif
int main()
{
float number = 0, max = 0, min = 0, sum = 0, ave = 0;
int count = 0;
max = number;
min = number;
//printf("Enter any number : ");
for (int i = 0; ; i++) {
printf("Enter any number : ");
scanf_s("%f", &number);
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
if (number == EOF) {
break;
}
}
printf("\n maximum is :%f ,& minimum is :%f ", max, min);
return 0;
}
when EOF or Ctrl D or any letter were entered
program just forever spams
"Enter any number :
keeps printing that and loot won't stop
i tried
1 2 3 4 5 6 7 8 9 10 11
for (int i = 0;i != EOF ; i++) {
printf("Enter any number : ");
scanf_s("%f", &number);
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
}
still same. I am using Windows 7 so I tried control z but still same .
please help!
scanf won't set number to EOF when it detects the end of input. It returns EOF. More generally, it returns the number of fields that it wrote values to, so in your case it will return 1 if it wrote something to number. Therefore you can detect that something went wrong (EOF or a non-numeric value entered) by comparing its return value to 1. And on windows, as you mentioned, you do need to enter ctrl-Z (and hit enter if I remember correctly) to signal eof.
#include <stdio.h>
int main() {
float number = 0, max = 0, min = 0;
printf("Enter any number : ");
if (scanf("%f", &number) == 1) {
max = min = number;
for (;;) {
printf("Enter any number : ");
if (scanf("%f", &number) != 1)
break;
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
}
}
printf("\nmaximum: %f, minimum: %f\n", max, min);
return 0;
}
No. If the user enter 123 then number will be equal to 123 and scanf will return 1. If the user enters "hello" then number will not be changed at all and scanf will return 0 (since it set 0 of the input fields). If the user enters Ctrl-Z then number will not be changed and scanf will return EOF (usually -1). Consider this function:
1 2 3 4 5 6 7 8 9 10 11 12
#include <stdio.h>
int myfunc(float *number) {
*number = 123.456; // sets number to 123.456
return 1; // returns 1
}
int main() {
float number = 0;
int ret = myfunc(&number);
printf("ret: %d\nnumber: %f\n", ret, number);
}