I have this text file called "input.txt" which contains:
test line one
test line two
final line
After compiling and running via
$ ./a.exe < input.txt
I get the output:
33 8 0
I'm confused as to why the line count doesn't work as when I print out the integer values, 13 and 10 (carriage return/line feed) are shown. Also charcount is two over the actual count. Any ideas?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int charcount = 0, wordcount = 0, linecount = 0;
int c = getchar();
while (c != EOF){
if (c == 13){
linecount++;
c = getchar();
} else if (c >= 65 && c <= 90 || c >= 97 && c <= 122 || c == 39 && c != 13) {
while (c >= 65 && c <= 90 || c >= 97 && c <= 122 || c == 39 && c != 13){
charcount++;
c = getchar();
}
wordcount++;
} else {
charcount++;
}
c = getchar();
}
printf("%lu %lu %lu\n", charcount, wordcount, linecount);
return (0);
}
When a text file on Windows is processed in C, the CRLF line endings are mapped to '\\n'
(newline) only endings. And '\\n'
is 10 ( Control-J ) and not 13 ( Control-M ). That's probably why you're seeing 0 for the line count.
You should not be coding the conditions as you did (unless you've got a sadistic teacher who tells you to do it like that). Use the <ctype.h>
and isalpha()
(and c == '\\''
instead of 39
).
You could debug by adding a print statement ( printf("^M read\\n");
) in the if (c == 13)
code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.