Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c++ - Reading characters from a File with fscanf

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...