【发布时间】:2014-07-08 22:43:27
【问题描述】:
我在向我的结构数组中添加整数时遇到问题,我不知道如何解决它。结构看起来像
struct info{
char name[20];
int course[5];
};
我使用 fgets 读取文件,然后使用 strtok() 标记该行,我相信它返回类型 char* 类型,因此读入的标记是 char* 类型的 1105。我尝试通过使用 atoi 将令牌转换为 int 类型然后将其存储到 struct_array[index].course = number; 来将其添加到我的结构数组中,但最终在编译时出现此错误。
hw4bcopy.c: In function ‘create_structures’:
hw4bcopy.c:48:44: error: incompatible types when assigning to type ‘int[5]’ from type ‘int’
struct_array[index].course = number;
我能够成功地将一个字符串输入到结构数组中,但声明有点不同,所以也许这就是原因。将字符串输入结构数组的声明是strcpy(struct_array[index].name,token);,所以我想我尝试将整数放入结构中的方式可能不正确?
在我尝试将令牌添加为整数之前,代码一切正常。
我正在做的是
- 打开文件
- 向函数发送文件
- tokenize 以获取名称的标记,例如
Edward和1105 - 将标记添加到数组结构中
代码是
struct info{
char name[20];
int course[5];
};
void create_structures(FILE* file);
int main()
{
FILE* fp = fopen("input-hw04b.txt","r");
FILE* nf = fopen("out2.txt","w+");
create_structures(fp);
}
void create_structures(FILE* file)
{
struct info struct_array[30];
char buffer[100];
char* del = " .";
char* token;
int number,count;int index = 0;
while(fgets(buffer,sizeof(buffer),file) != NULL)
{
count = 0;
token = strtok(buffer,del);
while(token != NULL)
{
if(count == 0)
{
strcpy(struct_array[index].name,token);
}
if(count == 5)
{
number = atoi(token);
struct_array[index].course = number;
}
token = strtok(NULL,del);
count = count + 1;
}
index = index +1;
}
int z;
for (z = 0; z < index; z++)
printf("%s %s\n",struct_array[z].name,struct_array[z].course);
【问题讨论】:
-
int course[5];-->int course; -
哇,谢谢,忘记改了
-
你真的应该做类似
strncpy(struct_array[index].name, token, 19);这样的事情,这样你就不会超出你的名字范围。 (告诉它不要复制超过 19 个字符,因为我们需要字符串末尾的'\0'空间)