tags:

views:

128

answers:

3

Difficulties appear in my homework again. I am writing a program to count the number of whitespace characters in a text file. I use "isspace" to count it. The content in the text file is "1 1 1", but the counter still 0, what's wrong of the codes?

#include "stdafx.h"
#include "ctype.h"
int _tmain(int argc, _TCHAR* argv[])
{

FILE* input; 
char x;
int space = 0;

input = fopen("123.txt", "r");

while ((fscanf(input, " %c", &x)) == 1)
{
   if (isspace(x)) 
   space++; 
}

printf("space : %d\n", space);

return 0;
}
+4  A: 

As I've pointed out before, you need to use fgetc(), not fscanf(). fscanf() doesn't read whitepace.

anon
The format string is wrong. Instead of " %c", if it were "%c", fscanf will work. "%c" in *scanf doesn't skip whitespace. I agree with your conclusion though: much easier to use fgetc/getc rather than fscanf, but using fscanf isn't wrong if one fixes the format string!
Alok
More accurately, the 'scanf' family of functions skip white space at the start of fields other than '%c'.
Jonathan Leffler
+4  A: 

scanf-family functions will automatically skip whitespace when it's present in the format string. Consider using fgetc instead.

ChrisV
+3  A: 

I think using fgetc (or getc) is a better solution in this case, but the other answers are wrong about fscanf in this case. The scanf family of functions will not skip whitespace if you use "%c" as the format. The reason your call doesn't work is because you have a whitespace in your format! So, instead of " %c" as the format, you need to use "%c" without the leading space. The leading space is telling fscanf: skip all whitespace and then give me the next non-whitespace character. fscanf does this, making sure that any value you get in x is not a whitespace. Thus, your isspace test is testing a condition that is already known to be false!

You can easily fix it by changing your format specification to "%c".

Having said that, I think it's much better to use fgetc/getc anyway because, as you have found out, scanf family of functions are hard to get right.

Alok