Properly Using EOF in C
I'm new to programming and I really want to learn writing a decent program. I am not exactly sure how to use EOF. My program was compiled and when I run it, it works fine except for the EOF part. The program is supposed to return a -1 value (after using CTRL+z) to the main function, and will print a statement then will close the program. The -1 is a different value from the -1 of EOF per se.
#include <stdio.h>
//Function Declaration
int inputFunction (int num);
int main (void)
{
//Local Declarations
int num;
do
{
inputFunction (num);
if (num < 0 || num > 100)
inputFunction (num);
else
inputFunction (num);
}while (num != -1);
return 0;
}
int inputFunction (int num)
{
int rc;
do
{
printf开发者_运维技巧("Enter an integer from 0 to 100: \n");
rc = scanf("%d", &num);
{
if (rc != EOF)
{
if (num < 0 || num >100)
{
printf("ERROR\n");
return num;
}
else
{
return num;
}
}
else
{
num = -1;
return num;
}
}
}while (rc != EOF);
}
The variable num
is never assigned in main
. You call inputFunction
and it returns a value, but you ignore the value it returns.
The ASCII value for CTRL-Z (^Z), which is often used as an end-of-file marker in DOS is 26 (decimal).And remember you are passing variable num in main as call by value not as reference so it would contain garbage value when you compare it.
As Gabe has stated you need to assign the return value of inputFunction() in order to use it - because variables in functions have local scope. So every time you are calling inputFunction() in main() you should be doing it like so:
num = inputFunction(num);
Otherwise the value of num in inputFunction() is lost when program execution returns to main(). This is the main reason your program is not performing as expected.
There are also some logic problems with your code. In the first if/else statement in main(), both statements produce exactly the same result. Other behaviour might not be exactly what you want to do either.
I think you might benefit from planning out with pen and paper what you want the program to do. One way is to "map out" what the program will do with arrows etc (a flowchart). Or you can start with a 1-2 sentence description of the goal, and then gradually expand that into more and more detail until you have a series of tasks that the program will do, which you can then convert to code.
精彩评论