我正在阅读有关 sscanf 的内容,我发现了这个:
Return Value Each of these functions [including s_sscanf()] returns the number of fields that are successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.
我正在对输入文件进行错误检查,我想确保获得有效的行,因此我尝试使用 sscanf,但如何确保该行中没有比我预期更多的字段。因此,如果我一行中有 3 个值,但我只需要两个,那么这对我来说是无效的行,但是当我使用 sscanf 时,我只读取 2 个变量,其余的将被忽略。我如何检查整行,确保行中没有垃圾,但我不确定会发生什么,所以它不像我可以添加另一个变量,因为用户可以输入任何内容。有人向我提到,您可以在 sscanf 函数中使用 * ,但我不太确定如何在代码中实现它的任何地方都找不到它。
最佳答案
scanf()
函数族返回成功分配的数量。如果代码需要三个输入项,则无法从 sscanf()
返回的值判断出来。无论是否提供了三个或更多输入项。
scanf()
函数的操作方式是读取一个字符,尝试匹配该字符,进行赋值(如果适用),然后移动到下一个字符或从函数调用返回。有一个转换说明符,%n
,它存储到目前为止在此过程中读取的字符数(不增加读取的字符数)。此转换说明符可用于确定输入是否已因调用sscanf()
而耗尽。 .
下面的代码提供了演示。 fgets()
收集的输入行包含换行符,除非输入太大而无法放入缓冲区数组。这里buffer[]
足够大来存储合理大小的输入,但更健壮的代码会更仔细地处理超大输入。当sscanf()
扫描输入字符串,依次读取每个字符,直到出现匹配失败或到达字符串末尾,因此匹配后预计读取的字符数"%d %d %d %n"
与输入字符串的长度相同,包括任何尾随空白字符。
#include <stdio.h>
#include <string.h>
#define BUF_SZ 1024
int main(void)
{
char buffer[BUF_SZ];
int x, y, z;
int pos;
printf("Enter three integers: ");
fflush(stdout);
// get user input
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
// first check: does input match 3 integers?
if (sscanf(buffer, "%d %d %d %n", &x, &y, &z, &pos) != 3) {
puts("Incorrectly formatted input");
} else {
// second check: did sscanf() finish at the end of the buffer?
int expected = strlen(buffer);
if (pos != expected) {
puts("Extra input in buffer");
printf("expected = %d, pos = %d\n", expected, pos);
} else {
// everything OK
printf("You entered: %d, %d, %d\n", x, y, z);
}
}
}
return 0;
}
交互示例:
>$ ./a.out
Enter three integers: 1 2 3
You entered: 1, 2, 3
>$ ./a.out
Enter three integers: 1 2
Incorrectly formatted input
>$ ./a.out
Enter three integers: 1 2 3 4
Extra input in buffer
expected = 8, pos = 6
如果希望禁止尾随空格字符, "%d %d %d%n"
可以用它代替。请注意,为了使其起作用,必须从 buffer[]
中删除换行符。这样它就不会被算作额外的输入。一种典型的方法是使用 buffer[strcspn(buffer, "\r\n")] = '\0'
:
int main(void)
{
char buffer[BUF_SZ];
int x, y, z;
int pos;
printf("Enter three integers: ");
fflush(stdout);
// get user input
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
// first check: does input match 3 integers?
if (sscanf(buffer, "%d %d %d%n", &x, &y, &z, &pos) != 3) {
puts("Incorrectly formatted input");
} else {
// remove trailing newline character
buffer[strcspn(buffer, "\r\n")] = '\0';
// second check: did sscanf() finish at the end of the buffer?
int expected = strlen(buffer);
if (pos != expected) {
puts("Extra input in buffer");
printf("expected = %d, pos = %d\n", expected, pos);
} else {
// everything OK
printf("You entered: %d, %d, %d\n", x, y, z);
}
}
}
return 0;
}
关于c - sscanf的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52874573/