我正在使用fscanf()来读取文件中的输入(我知道我应该使用fgets()但我不允许)并且我无法弄清楚如何正确使用格式字符串。
输入格式为:M 03f8ab8,1
我需要将每个字母,地址和数字保存到变量中。这是我到目前为止所得到的:
while(fscanf(file, " %s %s, %d", operation, address, &size) != -1)
如上所述,它将字母放入正确的var(操作)中,但将数字添加到地址的末尾,然后为size变量分配一些未定义的内容。
它应该将每个变量放入各自的变量中(并忽略逗号)
如何设置fscanf()才能正确获取?
这里的问题是"%s"
格式读取空格分隔的字符串,并且由于03f8ab8,1
中没有空格,因此它将全部读取为单个字符串。
您可以使用"%["
格式来解决这个问题,它允许您进行一些非常简单的模式匹配。例如,您可以使用它来告诉fscanf
读取所有内容,直到(但不包括)逗号。喜欢
fscanf(file, "%s %[^,], %d", operation, address, &size)
参见例如this scanf
(and family) reference了解更多详情。
此外,您不应该将fscanf
的结果与-1
进行比较,而是通过将回报与3
进行比较来检查它是否解析了正确数量的序列:
while (fscanf(file, "%s %[^,], %d", operation, address, &size) == 3) ...
请注意,上述格式不会对它将读取的字符串施加任何限制。这可能会导致你的字符串溢出。如果您的字符串具有固定大小(即它们是数组),则使用格式最大字段宽度来限制fscanf
将读取并放入数组的字符数。
例如(完全不了解您的实际字符串/数组):
while (fscanf(file, "%1s %8[^,], %d", operation, address, &size) == 3) ...
如上所述,第一个字符串不能长于一个单个字符,第二个字符串不能超过八个字符。请注意,这些数字不包括字符串null-terminator(您的数组中需要的空间超出上面给出的大小)。
fscanf(input_fp, "%30[^ ,\n\t]%30[^ ,\n\t]%30[^ ,\n\t]", ...
不消耗文本文件中的','和'\ n'。随后的fscanf()尝试也会失败并返回值0(不是EOF)会导致无限循环。
fscanf()
解决方案,对fgets()/sscanf()
更好地处理潜在的IO和解析错误:
main()
{
FILE *input_fp;
FILE *output_fp;
char buf[100];
while (fgets(buf, sizeof buf, input_fp) != NULL)
{
char name[30]; // Insure this size is 1 more than the width in scanf format.
char age_array[30];
char occupation[30];
#define VFMT " %29[^ ,\n\t]"
int n; // Use to check for trailing junk
if (3 == sscanf(buf, VFMT "," VFMT "," VFMT " %n",
name, age_array, occupation, &n) && buf[n] == '\0')
{
// Suspect OP really wants this width to be 1 more
if (fprintf(output_fp, "%-30s%-30s%-30s\n", name, age_array, occupation) < 0)
break;
} else
break; // format error
}
fclose(input_fp);
fclose(output_fp);
}
而不是调用ferror(),检查fgets(),fprintf()的返回值。
怀疑OP未声明的字段缓冲区为[30]并相应地调整了scanf()。
有关if (3 == sscanf(buf, VFMT "," ...
的详细信息
在以下情况下,if (3 == sscanf(...) && buf[n] == '\0') {
成为现实:
1)正好3个"%29[^ ,\n\t]"
格式说明每个scanf至少1个字符。
2)buf [n]是字符串的结尾。 n通过“%n”说明符设置。前面的''in“%n”会导致在最后一个"%29[^ ,\n\t]"
之后使用任何后续的空格。 scanf()看到“%n”,它指示它设置从扫描开始的当前偏移量,以分配给&n指向的int。
"VFMT "," VFMT "," VFMT " %n"
由编译器连接到
" %29[^ ,\n\t], %29[^ ,\n\t], %29[^ ,\n\t] %n".
我发现前者比后者更容易维护。
" %29[^ ,\n\t]"
中的第一个空格指示sscanf()扫描(消耗而不是保存)0个或更多个空格('','\ t','\ n'等)。其余的指示sscanf()使用并保存除“,”,“\ n”,“\ t”之外的任何1到29个字符,然后追加“\ 0”。