Reading characters from a File with fscanf

2019-09-21 23:42发布

问题:

I have a problem, using fscanf function :( I need to reed a sequence of characters from file like "a b c d" (characters are separated by space).

but it doesn't works :( how I have to read them? (

I tried to print it and the result is uncorrect. I think, it's because of spaces. I really don't know why it doesn't work.

Tell me please, what is wrong with array access?

回答1:

Add white space before %c =>

while (fscanf(pFile," %c", &alpArr[i++]) == 1); 

It should work.



回答2:

From cplusplus.com:

The function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

Then if your code is:

while ( fscanf(fin,"%c", &array[i++]) == 1 );

and your file is like this:

h e l l o

Your array will be:

[h][ ][e][ ][l][ ][l][ ][o]

If you change your code into:

while ( fscanf(fin," %c", &array[i++]) == 1 );

with the same file your array will be:

[h][e][l][l][o]

In any case the code works: it depends on what you want.

Anyway, you should think about starting to use fgets() + sscanf(), for example:

char buff[NUM];

while ( fgets(buff, sizeof buff, fin) )
    sscanf(buff,"%c", &array[i++]);

With the single fscanf() the lack of buffer management can turns into buffer overflow problems.



标签: c++ c file char scanf