Trouble reading a line using fscanf()

后端 未结 7 757
暖寄归人
暖寄归人 2020-12-01 15:40

I\'m trying to read a line using the following code:

while(fscanf(f, \"%[^\\n\\r]s\", cLine) != EOF )
{
    /* do something with cLine */
}

7条回答
  •  心在旅途
    2020-12-01 15:51

    If you try while( fscanf( f, "%27[^\n\r]", cLine ) == 1 ) you might have a little more luck. The three changes from your original:

    • length-limit what gets read in - I've used 27 here as an example, and unfortunately the scanf() family require the field width literally in the format string and can't use the * mechanism that the printf() can for passing the value in
    • get rid of the s in the format string - %[ is the format specifier for "all characters matching or not matching a set", and the set is terminated by a ] on its own
    • compare the return value against the number of conversions you expect to happen (and for ease of management, ensure that number is 1)

    That said, you'll get the same result with less pain by using fgets() to read in as much of a line as will fit in your buffer.

提交回复
热议问题