简体   繁体   中英

C - fscanf Mixed Numbers and Static Text

I am trying to read a file formatted in this general way:

Text Description: 12
Description2: 1
More descriptive things: 6

And I would like to read the numbers 12, 1, and 6 into variables.

I have tried code like this:

fscanf(fptr, "Text Description:%d",&desc1);
fscanf(fptr, "Description2:%d",&desc2);
fscanf(fptr, "More descriptive things:%d",&desc3);

But for some reason only the first variable is being populated. Does anyone know why this is the case?

Add space at the beginning of the string format to avoid the new line problems

fscanf(fptr, " Text Description:%d",&desc1);
fscanf(fptr, " Description2:%d",&desc2);
fscanf(fptr, " More descriptive things:%d",&desc3);

You aren't reading the newline once you've processed the 12, so the other two calls are finding that instead of the string or integer and therefore failing. You can use a space in the next fscanf call (which consumes all whitespace characters preceding the string you want to match). Alternatively you can consume it with a call to fgetc , as long as each line ends immediately with a linefeed, eg

fscanf(fptr, "Text Description:%d",&desc1);
fgetc(fptr); // drop the next character
fscanf(fptr, "Description2:%d",&desc2);

Dropping all stream input after the integer and up to the next '\\n' can be done with a loop instead:

while (fgetc(fptr) != '\n')
   ;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM