tags:

views:

45

answers:

3

Hi !

Have a problem with fscanf() - it does not skip to the next word after reading 10 characters from the file

while(fscanf(TEXT_FILE,"%10s", str) != EOF) // reads up to 10 char into str  

If it find the word that is greater than 10 characters, it will read 10 characters, store them into str, continue in the same word reading up to 10 characters.

How would I specify to read up to 10 char and skip to the next word ?
Is there an alternative ?

Thanks !

+2  A: 

You're probably better off using fgets() and strtok(), or writing a little loop around fgetc() to do what you want. fscanf() is flexible, but doesn't solve every problem.

Oli Charlesworth
Indeed, not only does it `fscanf()` not solve every problem, it also manages to create problems.
Jonathan Leffler
+1  A: 

You would have to continue scanning or calling fgetc into a throw-away buffer inside the body of that loop until the stream has consumed all the remaining non-whitespace chars in that word.

fscanf just scans upto 10 chars in the next word and leaves the file pointer at the end of what it read, on the next call it'll start from 10 chars into the string and have know idea that this isn't the start of a word so it'll treat the next 10 chars as one word too...

see strtok for what you probably want to do.

tobyodavies
A: 

I've found a solution for you:

while(fscanf(file, "%10s%*s", str) != EOF)

It works on VS 2008. I'm not sure if it is standard or not, and if your compiler will support it or not. The %*s part will skip current string (if it is having length greater than 10) upto next whitespace character and will consume all whitespace characters.

Donotalo