2

我想要做的是从文件中读取输入,该文件的格式为Data1;Data2;Data3;Data4;Data5我想标记这个字符串,并将这些单独的信​​息中的每一个存储在一个结构中,例如;

struct example {
    char data1[10];
    char data2[10];
    char data3[10];
    char data4[10];
    char data5[10];
};

到目前为止,这是我的输入功能:

void userInput() { // I will need to change return type
    FILE *file;
    char buffer[BUFFER_SIZE];
    struct example data[5];

    file = fopen(DATA, "r");

    if(file == NULL) {
        printf("Error opening data file.\n");
    }

    while(fgets(buffer, BUFFER_SIZE, file) != null) {
        //tokenize strings, and add to struct here
    }
}

我意识到在我的 while 函数中,我需要类似的东西:

....
char *token = NULL;
token = strtok(string, ";");

while(token != NULL) {
    // add to struct here
    token = strtok(NULL, ";");
}

有人可以解释我将如何循环通过我的结构来添加它吗?或者如果我什至以正确的方式解决这个问题?

4

2 回答 2

1

You have two things you want to iterate over. I assume each line of input corresponds to a different struct example. Then, you want to iterate over each field in your structure. You need a counter to iterate over your data array, and then you need a mechanism to iterate over the fields. I would use a temporary array to accomplish that:

int i = 0;
while(fgets(buffer, BUFFER_SIZE, file) != null && i < 5) {
    char *fields[] = {
        data[i].data1, data[i].data2, data[i].data3,
        data[i].data4, data[i].data5
    };
    size_t lengths[] = {
        sizeof(data[i].data1), sizeof(data[i].data2), sizeof(data[i].data3),
        sizeof(data[i].data4), sizeof(data[i].data5)
    };
    char *token = NULL;
    int j = 0;
    token = strtok(string, ";");
    while(token != NULL && j < 5) {
        snprintf(fields[j], lengths[j], "%s", token);
        token = strtok(NULL, ";");
        ++j;
    }
    ++i;
}
于 2013-10-01T20:25:48.093 回答
0

如果要使用结构,则需要某种计数器来区分结构元素。就像是:

int x = 0;
while(token != NULL) {

    token = strtok(NULL, ";");

    // add to struct here

    if (x == 0){
        data1 = token;
    }else if (x == 1){
        data2 = token;
    }else if (...)
    // ... keep going

    x++;
}
于 2013-10-01T20:12:55.283 回答