![](/img/trans.png)
[英]Subscripted value is neither array nor pointer nor vector at array index
[英]Line 90:subscripted value is neither array nor pointer nor vector
我創建了下面的程序來從文件中讀取逗號分隔的數據,然后插入到結構中。 有一個函數叫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);
我找到了一種簡單的方法。 我創建了一個名為char g[100]
的變量,然后將line[i]
int保存到g[100]
。 然后將g[]
轉換為p.Id
char g[100];
for( j=0 ; line[i]!='\0';i++, j++){
g[j]=line[i];
}
g[j]='\0';
p.Id=atoi(g);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.