C 第90行:下标值既不是数组,也不是指针,也不是向量
我创建了下面的程序,从文件中读取逗号分隔的数据,然后插入到结构中。有一个名为struct person insert_的函数,它将_插入到_structchar行[]中。当我在该函数中编译时,最后一个for循环p.Id[j]=行[I];出错了C 第90行:下标值既不是数组,也不是指针,也不是向量,c,C,我创建了下面的程序,从文件中读取逗号分隔的数据,然后插入到结构中。有一个名为struct person insert_的函数,它将_插入到_structchar行[]中。当我在该函数中编译时,最后一个for循环p.Id[j]=行[I];出错了 line 90 error: subscripted value is neither array nor pointer nor vector 这是密码 #include<stdio.h> #include<string.h>
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);
}
将此函数添加到代码中,以将字符串转换为数字atoi函数:
int atoi(char* str)
{
if(!str)
printf("Enter valid string");
int number = 0;
char* p = str;
while((*p >= '0') && (*p <= '9'))
{
number = number * 10 + (*p - '0');
p++;
}
return number;
}
写:
p.Id = atoi(line);
我找到了一个简单的方法。
我创建了一个名为char g[100]的变量,然后将行[I]int保存到g[100]。然后将g[]转换为p.Id
还有其他解决方案吗?因为我需要Id作为整数。我必须在代码之后对Id进行排序。我不需要每个结构都使用int数组。每个strcut.atoi的普通int-Id是正确的函数,但是使用atoiline可以从行的开头读取整数。可以尝试将Id存储为字符串。将其存储为int。这是一个猜测。我不想计数来定位传说中的第90行。您不必计数。转到struct person insert_into_structchar line[]然后最后一个for循环。我猜对了,因为该行包含p.Id[j]-这是您试图访问int Id作为指针、数组的地方,或者向量。谢谢。我知道了。但是有没有办法通过使用第[I]行来存储p.Id?只有在源文件中的所有Id都是1位数长的情况下。您知道第[i]行只有一个字符吗?
p.Id = atoi(line);
char g[100];
for( j=0 ; line[i]!='\0';i++, j++){
g[j]=line[i];
}
g[j]='\0';
p.Id=atoi(g);