how to ignore whitespaces in fscanf()

后端 未结 3 770
暖寄归人
暖寄归人 2021-01-18 08:33

I need to use fscanf to ignore all the white spaces and to not keep it. I tried to use something like the combination between (*) and [^\\n]<

相关标签:
3条回答
  • 2021-01-18 08:39

    Using a space (" ") in the fscanf format causes it to read and discard whitespace on the input until it finds a non-whitespace character, leaving that non-whitespace character on the input as the next character to be read. So you can do things like:

    fscanf(file, " "); // skip whitespace
    getc(file);        // get the non-whitespace character
    fscanf(file, " "); // skip whitespace
    getc(file);        // get the non-whitespace character
    

    or

    fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each
    

    from:

    Ignoring whitepace with fscanf or fgets?

    0 讨论(0)
  • 2021-01-18 08:56

    from the fscanf man page:

       A directive is one of the following:
      ·      A sequence of white-space characters (space, tab, newline, etc.;
              see isspace(3)).  This directive matches  any  amount  of  white
              space, including none, in the input.
    

    so

    fscanf(file, " %s\n");
    

    will skip all whitespace before reading in characters.

    0 讨论(0)
  • 2021-01-18 09:04

    Your code is crashing because you have a %s in your format specifier in the fscanf call, and you don't pass fscanf a char * to which you want it to write the string it finds.

    See http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html.

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