为什么这个字符数组(C语言)的打印量超过了它的容量?
我有这个为什么这个字符数组(C语言)的打印量超过了它的容量?,c,arrays,file-io,C,Arrays,File Io,我有这个int计数[1]这个数组给我3 Rab输出!但它只有2个容量,我想知道为什么 struct MEMBERS { int code; char Fname[40]; char Lname[40]; int Pnum[20]; float bedeh; float credit; int count[1]; struct meroDate issued; struct meroDate duedate; }; struc
int计数[1]
这个数组给我3 Rab
输出!但它只有2个容量,我想知道为什么
struct MEMBERS
{
int code;
char Fname[40];
char Lname[40];
int Pnum[20];
float bedeh;
float credit;
int count[1];
struct meroDate issued;
struct meroDate duedate;
};
struct MEMBERS b;
int main()
{
int i = 0, line = 5;
char w[100];
int str[100];
FILE *myfile;
myfile = fopen("Members.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fgets(str,2,myfile);
strncpy(b.count, str, 1);
i++;
printf("%s",b.count);
}
fclose(myfile);
return 0;
}
myMembers.txt
包含:
3
Rebaz salimi 3840221821 09188888888
4
95120486525
95120482642
count
是一个只能包含一个元素的整数数组。您将其传递给需要char*
作为参数的函数,从而导致未定义的行为
printf("%s",b.count); // %s expects char * not int[]
同样在这里-
strncpy(b.count, str, 1);
您需要使用循环或使用手动复制,具体取决于您的数据
编辑:-
fgets(str,2,myfile);
if(sscanf(str, "%d", &b.count[0])==1){
printf("%d\n", b.count[0]);
i++;
}
从文件中读取并存储在b.count[0]
中,检查sscanf的返回,如果成功,则打印其值
而且
fgets(str,2,myfile);
^^^ str is int[] but fgets requires argument as char *.
所以str
应该是char*
类型 count
是一个只能包含一个元素的整数数组。您将其传递给需要char*
作为参数的函数,从而导致未定义的行为
printf("%s",b.count); // %s expects char * not int[]
同样在这里-
strncpy(b.count, str, 1);
您需要使用循环或使用手动复制,具体取决于您的数据
编辑:-
fgets(str,2,myfile);
if(sscanf(str, "%d", &b.count[0])==1){
printf("%d\n", b.count[0]);
i++;
}
从文件中读取并存储在b.count[0]
中,检查sscanf的返回,如果成功,则打印其值
而且
fgets(str,2,myfile);
^^^ str is int[] but fgets requires argument as char *.
所以str
应该是char*
类型 int[]
不是字符串。所以,printf(“%s”,b.count)代码>不是您想要使用的。使用for循环逐个打印int[]
的内容,或使用char*
打印。我强烈建议您启用所有编译器警告。int[]
不是字符串。所以,printf(“%s”,b.count)代码>不是您想要使用的。使用for循环逐个打印int[]
的内容,或者使用char*
。我强烈建议您启用所有编译器警告。那个么,您建议我只获取数字3作为“b.count”@moh89的唯一整数输出,您希望从中获得什么输出?显然,您只能在整数数组中存储整数。对于字符串部分,您需要做一些其他操作。我只需要获取第一行整数并将其存储在“int count[1]”中,那么您建议我仅获取数字3作为“b.count”@moh89的唯一整数输出,您希望从中获得什么输出?显然,您只能在整数数组中存储整数。对于字符串部分,您需要执行其他操作。我只需要获取第一行整数并将其存储在“int count[1]”中