Hello. I am new to programming and I am kinda of stuck on this code I have written. I am trying to count lines, words and characters in a file. I am having sorta of trouble counting the words and have been trying to figure it out for a couple of hours now. I know to some it may be easy.
Here is the code.
Code:
int main (int argc, char *argv[]){
FILE *input;
int character, newword,newline, state;
int c;
state = OUT;
character = newword = newline= 0;
input = fopen(argv[1], "r");
if ( input == NULL){
printf("Error! Can not read from file\n");
exit(-1);
}
if (argc !=2){
printf("Not enough arguments provided\n");
exit(-1);
}
if (argc>2){
printf("Too many arguments were provided\n");
exit(-1);
}
while ((c = fgetc(input)) != EOF){
if ( c == '\n'){
state= OUT;
newline++;
}
if ( c >='a' && c<= 'z'){
state = IN;
character++;
}
if (c >='A' && c<= 'Z'){
state = IN;
character++;
}
if ( c >= '0' && c<='9'){
state = IN;
character++;
}
else {;}
if (c == ' ' ||c == '\n'|| c == '\t'){
state = OUT;
newword++;
}
}
printf("The number of lines: %d\n",newline);
printf("The number of words: %d\n", newword);
printf("The number of characters: %d\n", character);
fclose(input);
}
In the text file, there is the following text,
J.K. Rowling's Harry Potter
It is suppose to print out:
The number of lines: 1
The number of words: 6
The number of characters: 21
However, my code makes it print out
The number of lines: 1
The number of words: 4
The number of characters: 21
Any suggestions?
Also, another bug I found is when I leave the text file with just
!
my code makes it seem as if ! is counted as a word.
Any suggestions to fix this as well?
Everything else is good, only the number of words is the problem.
Thank you!