Can fscanf() read whitespace?

后端 未结 6 1840
野趣味
野趣味 2020-12-09 00:29

I\'ve already got some code to read a text file using fscanf(), and now I need it modified so that fields that were previously whitespace-free need to allow whi

6条回答
  •  旧巷少年郎
    2020-12-09 01:17

    A %s specifier in fscanf skips any whitespace on the input, then reads a string of non-whitespace characters up to and not including the next whitespace character.

    If you want to read up to a newline, you can use %[^\n] as a specifier. In addition, a ' ' in the format string will skip whitespace on the input. So if you use

    fscanf("%*s %[^\n]", &str);
    

    it will read the first thing on the line up to the first whitespace ("title:" in your case), and throw it away, then will read whitespace chars and throw them away, then will read all chars up to a newline into str, which sounds like what you want.

    Be careful that str doesn't overflow -- you might want to use

    fscanf("%*s %100[^\n]", &str)
    

    to limit the maximum string length you'll read (100 characters, not counting a terminating NUL here).

提交回复
热议问题