How to use a loop function with user input in C? - Stack Overflow
Checking for EOF in 6 places can't be the best way, right?
Also, some indenting might reveal some bugs:
Code:
case ('*'):
printf("%f * %f = %f \n)", i, j, i * j);
if ( feof(cmd) )
break; /* break happens only if ... */
case ('/'):
printf("%f / %f = %f \n)", i, j, i / j);
if ( feof(cmd) )
break;
Cases "fall through" each other unless you break; in this case the break refers to the switch, not the loop. You both forgot to break from your cases and mistakenly thought you could exit the loop from within the switch. You'll need something else for that. And why copy the op in your printf format strings when you already have op?
Code:
#include <stdio.h>
#include <stdlib.h>
/* Removed unused macro */
int main(void)
{
float i, j;
char op; /* H and Q are not used */
/* Might as well initialize rather than assign */
FILE* cmd = fopen("CommandsProj1.dat", "r");
if (cmd == NULL)
{
printf("File could not be opened");
return EXIT_FAILURE; /* Something other than zero */
}
/* Better to keep success in same scope as call, so no 'else' here. */
/* fscanf returns EOF if it tries to read but
* isn't able to get any data. So you can put your reading in
* the loop condition, and when you get to the
* one-after-last-line, this will be false and
* your loop will be done.
*/
while (EOF != fscanf(cmd, "%c %f %f", &op, &i, &j))
{
float result;
switch (op)
{
case '+': /* No need for parentheses around the case expressions */
result = i + j;
break; /* Breaks from the switch */
case '-':
result = i - j;
break;
case '*':
result = i * j;
break;
case '/':
result = i / j;
break;
case 'h': /* why not allow lower case too? */
case 'H':
printf("Help Menu Coming soon\n");
continue; /* Continues the loop */
case 'q':
case 'Q':
printf("Goodbye");
goto cleanupArea;
/* goto could be avoided using functions
or a "quitting" flag, if you wish */
default:
continue; /* So we skip the printf */
}
/* reused 'op' here, and removed the ')' */
printf("%f %c %f = %f \n", i, op, j, result);
}
cleanupArea:
fclose(cmd);
return EXIT_SUCCESS; /* The official zero */
}