简体   繁体   中英

fscanf return value for a string

Still new to coding and I'm really confused with this one. I searched up that fscanf returns the number of successfully assigned characters so why does the code below return 1 instead of 4?

string temp;
int len;

len = fscanf(fp, "%[^-,]s", temp);
printf("\n%s", temp);
printf("\nlen: %d", len);
temp[len] = '\0';

Output:

2020

len: 1

I searched up that fscanf returns the number of successfully assigned characters

No. The fscanf() returns the number of successfully assigned input items .

From the documentation of fscanf(3) ,

RETURN VALUE

Upon successful completion, these functions shall return the number of successfully matched and assigned input items ; this number can be zero in the event of an early matching failure.

So, remember that len = fscanf(...) is not going to return the length of the characters that are correctly initialized, but the number of successfully assigned input items. In this case, it is 1 and that is correct.

len = fscanf(fp, "%[^-,]s", temp);

  • The format specifier for an exclusion set %[^-,] does not require or include a trailing s .

  • The return value of fscanf is the number of items assigned, not the character count.

  • Also, temp[len] = '\0'; is wrong here, and redundant in general.

The following shows how to correctly parse the first -, delimited token, with full error checking and using %n to retrieve the number of characters actually consumed.

#include <stdio.h>

int main()
{
  const char str[] = "2021-02-12";

  char tok[79 + 1];                                // `%79s` or similar to prevent buffer overrun
  int len;                                         // number of characters actually parsed
  int cnt = sscanf(str, "%79[^-,]%n", tok, &len);  // number of items matched and assigned

  if(cnt != 1)
  {   printf("error reading token\n"); return 1; }

  printf("input: \"%s\"\n", str);
  printf("items: %d\n", cnt);
  printf("chars: %d\n", len);
  printf("token: \"%s\"\n", tok);
  printf("remaining: \"%s\"\n", str + len);

  return 0;
}

Output :

input: "2021-02-12"
items: 1
chars: 4
token: "2021"
remaining: "-02-12"

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