简体   繁体   中英

sscanf - reading from empty string

When I pass an empty string to sscanf , it returns zero and it doesn't change the given variable.

char* ptr = "";
abc = sscanf(ptr, "%s", output);
// abc == 0

Can you let me know the way to work it out?

sscanf awaits the first argument to be the C string that the function processes as its source to retrieve the data . Passing an empty string to this function can't yield your variable to be initialized, since there is nothing this function would initialize it with.

Also note that On success, the function returns the number of variables filled. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

Following code, compiled with MinGW (gcc-core 4.5.0-1)

char str[10];
int ret = sscanf("", "%9s", str);
printf("%d\n", ret);

outputs -1 (EOF)

Good way of checking whether sscanf was successful is to check whether it's return value is really equal to the number of provided variables. In this case it would be if (ret == 1) . Although many people just check, whether value greater than 0 was returned, to make sure that something has been read and that no error has occurred.

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