fscanf and newline character

前端 未结 3 1746
南笙
南笙 2020-12-17 15:30

I have fscanf to read lines of setting from a configuration file. Those settings have strictly predefined format which looks like

name1=option1;
name2=option         


        
相关标签:
3条回答
  • 2020-12-17 16:05

    This will work:

    fscanf(configuration,"%[^=]=%[^;];%[^\n]",name,option,dummy);

    You will have to consume the new line character.Otherwise,the newline is left in the input stream.

    0 讨论(0)
  • 2020-12-17 16:11

    Just add space at the end of the format string:

    "%[^=]=%[^;]; "
    

    This will eat all whitespace characters, including new-lines.

    Quotation from cplusplus.com:

    Whitespace character: 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).

    0 讨论(0)
  • 2020-12-17 16:13

    An alternative is to use fgets() to read the entire line into a string, then use sscanf(). This has an advantage in debugging in that you can see exactly what data the function is working on.

    0 讨论(0)
提交回复
热议问题