我在下面的程序中创建了从文件中读取逗号分隔的数据,然后插入到结构中。有一个叫struct person insert_into_struct(char line[])
的功能。当我编译这个在函数中的最后一个for循环p.Id[j]=line[i];
得到一个错误第90行:下标值既不是数组也不是指针也不是矢量
line 90 error: subscripted value is neither array nor pointer nor vector
这是代码
#include<stdio.h>
#include<string.h>
struct person{
char name[100];
char address[100];
int Id;
};
struct person insert_into_struct(char line[]);
int main(int argc,char *argv[]){
FILE *fp1;
fp1=fopen(argv[1],"r");
char ch;
char line[100];
int i=0;
struct person person_arry[100];
int linenum=0;
if(fp1==0)
{
printf("Error\n");
}
else
{
while((ch=fgetc(fp1))!=EOF){
switch(ch){
case '\n':
line[i]='\0';
person_arry[linenum]=insert_into_struct(line);
printf("line:%d, name: %s, address: %s, id: %s\n",
linenum,
person_arry[linenum].name,
person_arry[linenum].address,
person_arry[linenum].Id);
linenum++;
i=0;
break;
default:
line[i]=ch;
i++;
}
}
}
return 0;
}
struct person insert_into_struct(char line[]){
int i,j=0;
// now we have to declare a temp structre to hold the seperated values
struct person p;
//now split the values one by one.
//first copy the name from line[] into p.name
for(i=0; line[i]!=',';i++, j++){
p.name[j]=line[i];
}
i++;
p.name[j]='\0';
//printf("name=%s\n", p.name);
//second copy the address in line[] to p.address[]
for(j=0 ; line[i]!=',';i++, j++){
p.address[j]=line[i];
}
i++;
p.address[j]='\0';
//printf("address=%s\n", p.address);
// Erroneous line:
//third copy the id in line[] to p.id[]
for(j=0 ; line[i]!='\0';i++, j++){
p.Id[j]=line[i];
}
p.Id[j]='\0';
//printf("Id=%s\n", p.Id);
return(p);
}
您尝试将'Id'作为字符串存储。将它存储为'int'。 (这是一个猜测,我不想指望找到那个传说中的“第90行”。) – usr2564301 2014-09-27 14:23:59
你不必数它。去结构人insert_into_struct(char line []),然后在那里循环。 – 2014-09-27 14:29:21
嗯,我猜对了,因为那行包含'p.Id [j]' - 这是你正在尝试访问'int id'作为指针,数组或者矢量的地方。 – usr2564301 2014-09-27 14:35:12