拆分一个长字符串(Splitting a long string)

2019-10-29 23:28发布

我有一个存档results.csv ,我需要阅读该归档的前两行,拆分第二个和打印出来的output.txt 。 不知怎的,它没有任何印刷,但我不知道原因。

我没有补充说我肯定是精细的功能。

命令: ac results.csv

第一行: date,home_team,away_team,home_score,away_score,tournament,city,country,neutral

下联: 18721130,Scotland,England,0,0,Friendly,Glasgow,Scotland,FALSE

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

typedef struct
{
    char *line1;
    long int date;
    char *h_team;
    char *a_team;
    int gols_h_team;
    int gols_a_team;
    char *reason;
    char *city;
    char *country;
    char *neutral_field;

}Data;

void alloc_Data(Data *d, int size)
{
d->line1 = (char*)malloc(50*sizeof(char)); 
d->h_team = (char*)malloc(30*sizeof(char)); 
d->a_team = (char*)malloc(30*sizeof(char)); 
d->reason = (char*)malloc(30*sizeof(char)); 
d->city = (char*)malloc(30*sizeof(char)); 
d->country = (char*)malloc(30*sizeof(char)); 
d->neutral_field = (char*)malloc(9*sizeof(char)); 
}

void store(Data *d, FILE *input, FILE *output, int size)
{

    fscanf(input,  "%s", d[0].line1);
    fprintf(output,  "%s\n", d[0].line1);

    for(int i = 1; i < size; i++)
    {
        fscanf(input, "%li,%[^,]s%[^,]s%d,%d,%[^,]s%[^,]s%[^,]s%[^,]s", &d[i].date, d[i].h_team, d[i].a_team, &d[i].gols_h_team, &d[i].gols_a_team, d[i].reason, d[i].city, d[i].country, d[i].neutral_field );
        fprintf(output, "%li,%s,%s,%d,%d,%s,%s,%s,%s\n", d[i].date, d[i].h_team, d[i].a_team, d[i].gols_h_team, d[i].gols_a_team, d[i].reason, d[i].city, d[i].country, d[i].neutral_field );

    }

}

int main(int argc, char *argv[])
{
    FILE *input;
    FILE *output;
    char *string = "output.txt";
    int size = 2;

    open_input(argv, &input);   
    open_output(string, &output);   

    Data *d;
    d = (Data*)malloc(size*sizeof(Data)); 
    alloc_Data(d, size);

    store(d, input, output, size);

    free(d);

    return 0;
}

Answer 1:

OP的fscanf()的格式与弄乱s%[^,]和缺失, 。 @Gem泰勒

更好的选择是读取使用所有线路fgets() (包括第一)

// fscanf(input, "%li,%[^,]s%[^,]s%d,%d,%[^,]s%[^,]s%[^,]s%[^,]s",...d[i].neutral_field );

#define EXPECTED_MAX_BUFFER_SIZE 150
char buffer[EXPECTED_MAX_BUFFER_SIZE * 2];  // suggest using 2x expected max size
if (fgets(buffer, sizeof buffer, input)) {

然后解析与球队成绩sscanf() 使用" %n"末是测试如果整个一个简单的方法sscanf()没有额外的垃圾成功。 sscanf()应得宽限制和复杂的扫描与一些定义受益来管理符。 注意没有s"%29[^,]"

    int n = 0;
    #define FDat "%li ,"
    #define FScr "%d ,"
    #define Ftxt " %29[^,],"
    #define Fneu " %8[^,]"
    sscanf(buffer, FDat Ftxt Ftxt FScr FScr Ftxt Ftxt Ftxt Fneu " %n", 
        &d[i].date, d[i].h_team, d[i].a_team, 
        &d[i].gols_h_team, &d[i].gols_a_team, 
        d[i].reason, d[i].city, d[i].country, d[i].neutral_field, &n);

    if (n > 0 && buffer[n] == '\0') {
      // success
      fprintf(output, ...
    } else {
      // bad input
    }


文章来源: Splitting a long string