简体   繁体   中英

Select the floating-point numbers from a file

I want to select the floating-point numbers from a file. What I thought as a solution was this:

while ( (ch= getc(fp)) != EOF )
{
   if( isdigit(ch))
      //do some stuff
}

However then I saw, that with this approach I get only the integers (but I want the float). So I looked it and I found this:

while( (fscanf(fp, "%lf", &n ) == 1)
   //do some stuff

I also looked the definition of the fscanf() and among other things it says..

Return Value

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.

However, I don't understand the while( (fscanf(fp, "%lf", &n ) == 1) . If fscanf() reads a float number will return 1, otherwise will return something else?

The fscanf call in your code will return 1 if it reads and converts one floating point value. If you had a format asking for two conversions (like, for example, "%lf %d" ) it would have returned 2 for success. In short, it will return the number of successfully parsed % formats you have in the format string.

If the input is not a floating point number, then fscanf will return 0 and therefore the loop will end. Or if there is an error or you have reached the end of the file it will return EOF , which also will break the loop.

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