I'm getting bugs in my program (that is supposed to find all ints in and file of chars and ints) where "feof" doesn't work (while loop never ends) or no integers are read/found unless the entire file is full of ints.
My code...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
FILE *ptr;
int val;
int i = 0;
char myChar;
int chc;
int result = 0;
ptr = fopen("stuff.txt", "w");
if(ptr == NULL)
{
printf("Could not open file \n");
}
for(; i < 5; ++i)
{
printf(" Char(0) or int(1)? ");
scanf("%d", &chc);
if(chc == 0)
{
printf(" Enter a char: ");
scanf(" %c", &myChar);
fprintf(ptr, " %c \n", myChar);
}
else
{
printf(" Enter an int: ");
scanf("%d", &val);
fprintf(ptr, " %d \n", val);
}
}
fclose(ptr);
FILE *rp;
rp = fopen("stuff.txt", "r");
if(ptr == NULL)
{
printf("Could not open file \n");
}
else
{
while(!feof(rp))
{
if(isdigit(fgetc(rp)))
{
++result;
}
}
}
printf(" Total numbers in file: %d\n", result);
return 0;
}
Edit:
I forgot to re-add "int result" and this is a new bug. Probably has to do with fgetc like someone mentioned. I get an extra one added to my total.
Solved: I'm reading 34 as "3" and "4", so it counts as two. Not sure how to marked as solved or if to delete this.
Char(0) or int(1)? 0
Enter a char: e
Char(0) or int(1)? 1
Enter an int: 34
Char(0) or int(1)? 0
Enter a char: p
Char(0) or int(1)? 0
Enter a char: d
Char(0) or int(1)? 0
Enter a char: u
Total numbers in file: 2