繁体   English   中英

C使用结构使用sscanf将fgets()char数组解析为多个变量

[英]C parsing fgets() char array into multiple variables with sscanf using structures

在此程序中,它编译但出现分段错误, 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数组中。

我评论了我尝试初始化为array的区域,该区域具有与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
}

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

只需用pos全局替换pos-1并增加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);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM