我正在尝试从文件中读取如下所示的行:
String1 A
String2 B
String3 C
等等..
并将它们存储在两个独立的结构体数组中;字符串名称和组。 我发现的所有内容都是由符号或其他类似代码分隔的字符串,但不是同一问题
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include <math.h>
#include "string.h"
struct StringStruct {
char Stringname[16];
char group[1];
}String[100];
int MaxNumLines = 100, i;
char str[25];
int main()
{
// open String.dat file as a read from file
FILE *fp1;
errno_t string_file = fopen_s(&fp1, "String.dat", "r");
// if String.dat not found,
if (fp1 == NULL)
{
// print error
printf_s("Error: String.dat not found\n");
exit(0);
}
// if String.dat found
else
{
// print success
printf_s("File String.dat opened successfully\n");
}
// read names and assign groups
while (fscanf_s(fp1, "%s %s", String[i].Stringname, String[i].group) != EOF)
{
// read names one line at a time
for (i = 0; i < MaxNumLines; i++)
{
// read string name
scanf_s(str, "%s %s", String[i].Stringname, String[i].group);
}
}
for (i = 0; i < MaxNumLines; i++)
{
printf_s("%-12s", String[i].Stringname);
printf_s("%s", String[i].group);
}
}
}
现在,在我看来一切都应该有效,但事实并非如此,而且我还收到了 fscanf_s 警告:
- warning C4477: 'fscanf_s' : format string '%s' requires an argument of type 'unsigned int', but variadic argument 2 has type 'char *'
- note: this argument is used as a buffer size
- warning C4473: 'fscanf_s' : not enough arguments passed for format string
- note: placeholders and their parameters expect 4 variadic arguments, but 2 were provided
- note: the missing variadic argument 3 is required by format string '%s'
- note: this argument is used by a conversion specifier
但我研究了 fscanf_s 函数,一切似乎都与它的使用描述一致。
我对C语言不是最精通的,但是到目前为止我已经在这一年的时间里学习它,并且几天来我一直在试图找到这些问题的解决方案,但是已经做出了当时没有任何进展。
最佳答案
使用 scanf_s
系列函数时,格式说明符 %s
、%c
和 %[
期望两个个参数,而不是一个。第一个是指向应存储数据的缓冲区的指针,第二个是该缓冲区的大小。
对于您的代码,它看起来像这样:
fscanf_s(fp1, "%s %s", String[i].Stringname, 16, String[i].group, 1)
请注意,常规 scanf
系列函数仅采用一个参数(指向缓冲区的指针)来指定这些格式。
可以找到有关这些函数的更多信息here .
关于c - 如何从 C 语言的文件中逐行读取每行两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50430633/