Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char** argv) {
FILE *textfile;
int max_chars = 1000;
int chars = 0;
int digits = 0;
char contents[max_chars];
char c;
textfile = fopen("file.txt", "r");
if (textfile == NULL) {
printf("Cannot open file.");
exit(8);
}
while ((c = fgetc(textfile)) != EOF) {
chars++;
}
fread(contents,max_chars,1,textfile);
printf("Characters in text file: %d\n", chars);
for (i = 0; i < chars; i++) {
if ((contents[i] != '\0') && (contents[i] != '\n') && (contents[i] != '\t')) {
if isdigit(contents[i]) {
printf("digit: %c\n",contents[i]);
digits++;
}
}
}
printf("Total digits: %d\n", digits);
fclose(textfile);
return (EXIT_SUCCESS);
}
file.txt:
Output:
Characters in text file: 15
digit: 4
Total digits: 1
I'm not understanding why it is only counting the 4 and not the other digits.