我有以下结构
typedef struct
{
char* city;
int temp;
} Place;`
我试图将一行中的两个值读入结构数组。
这些行看起来像:
Los Angeles; 88
我正在尝试将数据读入数组。假设我的内存分配是正确的,那么读取这些值的正确方法是什么。
我的代码
void readData(FILE** fpData, FILE** fpOutput)
{
char s[100];
int index = 0;
Place *values;
values=malloc(size * sizeof(Place));
if (values == NULL)
{
MEM_ERROR;
exit(1);
}
for (int a = 0; a < size; a++)
{
(values[a]).city = (char *) malloc(100 * sizeof(char));
if(values[a].city == NULL)
{
MEM_ERROR;
exit(100);
}
}
while(fgets(s, sizeof(s), *fpData)!=NULL)
{
sscanf(s, "%[^:]%*c%d\n", values[index].city, &values[index].temp);
index++;
}
sortInsertion(values, size, fpOutput);
free(values);
return;
}
城市没有进入数组,所以我假设它说 values[index].city 的部分是不正确的。
我该如何解决这个问题?
最佳答案
您的数据使用分号 ;
而您的 sscanf
格式使用冒号 :
,请确保这是相同的字符。如果你的数据确实使用了分号,将sscanf
格式中的%[^:]
部分改成%[^;]
这是我的代码以及我如何运行它以向您展示它的工作原理:
#include <stdio.h>
struct Place {
char city[100];
int temp;
} values[30];
int main() {
char s[100];
int i=0, n=0;
while ( fgets(s, sizeof(s), stdin) != NULL ) {
sscanf(s, "%[^;]%*c%d\n", values[n].city, &values[n].temp);
n++;
}
printf("n=%d\n", n);
for ( i=0; i<n; i++ ) {
printf("values[%d] = (%s, %d)\n", i, values[i].city, values[i].temp);
}
}
这是我在 Linux 上运行它的方式:
% for a in `seq 1 3`; do echo "City-$a; $a$a"; done | ./a.out
n=3
values[0] = (City-1, 11)
values[1] = (City-2, 22)
values[2] = (City-3, 33)
关于c - 如何将指针值读入结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712085/