简体   繁体   中英

How to read float type numbers with special characters from a file

I want to read a float type number from a txt file like this:

American history 91 12.9% 8 1

But if I read with

fscanf(file, "%s %d %f %d %d", major, &number1, &percentage, &number2, &number3);

it gives me an error since there is a special character involved. What should I do to just take out only the float part?

It's not failing because of the percent sign, but because your format string is wrong. %s doesn't read an arbitrary string, it reads characters up to the first whitespace, ie "American". fscanf will fail after that. Hint: look up [ .

To get past the % though, all you need to do is have this in your format string: %f%% (read a float, match a % ).

From the manpage :

%

Matches a literal '%'. That is, %% in the format string matches a single input '%' character. No conversion is done (but initial white space characters are discarded), and assignment does not occur.


Example:

#include <stdio.h>

int main() {
    float a, b;
    scanf("%f%%%f", &a, &b);
    printf("%f, %f\n", a, b);
    return 0;
}

Output:

$ gcc test.c && echo "1.2%3.4" | ./a.out
1.200000, 3.400000

use backslash() as an escape character

fscanf(file, "%s %d %f\\% %d %d", major, &number1, &percentage, &number2, &number3);

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