gpt4 book ai didi

c - 第 90 行 :subscripted value is neither array nor pointer nor vector

转载 作者:行者123 更新时间:2023-11-30 17:28:20 24 4
gpt4 key购买 nike

我创建了下面的程序来从文件中读取逗号分隔的数据,然后插入到结构中。有一个名为 struct person insert_into_struct(char line[]) 的函数。当我在该函数中编译此函数时,在最后一个 for 循环中 p.Id[j]=line[i]; 出现错误

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;
}

然后像这样实现:

而不是

 for( j=0 ; line[i]!='\0';i++, j++){
p.Id[j]=line[i];
}

写:

p.Id = atoi(line);

关于c - 第 90 行 :subscripted value is neither array nor pointer nor vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com