1

在这个程序中它编译但我得到分段错误,sscanf(str, "%d %s %s %d %f", &pos, z[pos-1].city, z[pos-1].state, &z[pos-1].population, &z[pos-1].growth);这是因为这一行z[pos-1].city, z[pos-1].state,没有 & 但是当我添加时我得到警告:format â%sâ expects type âchar *â, but argument 4 has type âchar (*)[200]â

我确定还有另一种方法可以做到这一点,我需要使用结构,将文件存储信息读入结构数组,然后显示该数组。printf 仅将城市和州存储到 char 数组中。

我评论了我试图初始化为数组的区域,并且有一个与 char 数组值全部三个不兼容的类型:a、'a'、“a”。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
    int rank;
    char city[200];
char state[50];
int population;
float growth;
}city_t;

void read_data(city_t *z)
{
    FILE *inp;
    inp = fopen("cities.dat", "r");
    char str[256];
    int pos = 0;
    if(inp==NULL)
    {
        printf("The input file does not exist\n");
    }
    else
    {
        /*reads and test until eof*/
        while(1)
        {
            /*if EOF break while loop*/
            if(feof(inp))
            {break;}
            else
            {
                /*read in a number into testNum*/
                //fscanf(inp, "%d", &testNum);
                fgets(str,sizeof(str),inp);
                sscanf(str, "%d %s %s %d %f", &pos, z[pos-1].city, z[pos-1].state, &z[pos-1].population, &z[pos-1].growth);
                z[pos-1].rank = pos;
            }
        }
    }
    fclose(inp);
}

void print_data(city_t *z, int size)
{
    int i;
    printf("rank\tcity\t\tstate\tpopulation\t\tgrowth\n");
    for(i=0;i<size;i++)
    {
        printf("%d\t%s\t\t%s\t\%d\t\t%f\n", z[i].rank, z[i].city, z[i].state, z[i].population, z[i].growth);
    }
}

int main()
{
    int i;
    city_t cities[10];
    /*for(i;i<10;i++)
    {
        cities[i].rank = 0;
        cities[i].city = "a";
        cities[i].state = "a";
        cities[i].population = 0;
        cities[i].growth = 0.00;
    }*/
    read_data(&cities[0]);
    print_data(&cities[0], 10);
    return(0);
}

{
dat file
1 New_York NY 8143197 9.4
2 Los_Angeles CA 3844829 6.0
3 Chicago IL 2842518 4.0
4 Houston TX 2016582 19.8
5 Philadelphia PA 1463281 -4.3
6 Phoenix AZ 1461575 34.3
7 San_Antonio TX 1256509 22.3
8 San_Diego CA 1255540 10.2
9 Dallas TX 1213825 18.0
10 San_Jose CA 912332 14.4
}
4

1 回答 1

0

在 read_data 中,您扫描到z[pos-1]....pos 从 0 开始的位置。因此,您将写入超出(之前)数组的扩展。

pos-1只需对withpos和 increment进行全局替换pos;你也可以使用 fscanf,所以你的阅读可以是:

 for (int pos=0; !feof(inp); ++pos)
 {
     fscanf(inp, "%d %s %s %d %f",
            &z[pos].rank,
            z[pos].city,
            z[pos].state,
            &z[pos].population,
            &z[pos].growth);
 }
于 2012-11-19T00:43:47.460 回答