簡體   English   中英

解析 CSV 文件問題

[英]Parsing a CSV File Problems

我嘗試將 csv 文件中給出的數據解析為“數據”文件中的 ID、AGE 和 GPA 字段,但我認為我做的不對(當我嘗試打印數據時,它打印出奇怪的數字)。 我究竟做錯了什么?

char data[1000];
FILE *x = fopen("database.csv","rt");
char NAME[300];
int ID[300],AGE[300],GPA[300];
int i,j;
i = 0;

while(!feof(x)) {

        fgets(data,999,x);

        for (j = 0; j < 300 && data[i] != ','; j++, i++) {
                ID[j] = data[i];
                i++;
        }

        for (j = 0; j < 300 && data[i] != ','; j++, i++) {
                NAME[j] = data[i];
                i++;
        }

        for (j = 0; j < 300 && ( data[i] != '\0' || data[i] != '\r' || data[i] != data[i] != '\n'); j++, i++) {

                GPA[j] = data[i];

        }

}

首先:對於您正在做的事情,您可能需要仔細查看 function strtokatoi宏。 但是鑒於您發布的代碼,這可能還是有點太高級了,所以我在這里采取了更長的方式。

假設這條線是這樣的

172,924,1182

那么你需要解析這些數字。 數字 172 實際上在 memory 中用兩個或四個字節表示,格式非常不同,字節“0”與數字 0 完全不同。您將讀取的是 ASCII 碼,即十進制的 48,或者十六進制的 0x30。

如果你把一個數字的ASCII值減去48,你會得到一個數字,因為幸運的是數字是按數字順序存儲的,所以“0”是48,“1”是49等等。

但是您仍然有將三個數字 1 7 2 轉換為 172 的問題。

因此,一旦您有了“數據”:(我添加了注釋代碼來處理 CSV 內的未引用、未轉義的文本字段,因為在您的問題中您提到了一個 AGE 字段,但是您似乎想使用一個 NAME 字段。文本字段被引用或轉義的情況完全是另一罐蠕蟲)

size_t i   = 0;
int number = 0;
int c;
int field = 0; // Fields start at 0 (ID).
// size_t x = 0;

// A for loop that never ends until we issue a "break"
for(;;) {
    c = data[i++];
    // What character did we just read?
    if ((',' == c) || (0x0c == c) || (0x0a == c) || (0x00 == c)) {
        // We have completed read of a number field. Which field was it?
        switch(field) {
            case 0: ID[j] = number; break;
            case 1: AGE[j] = number; break;
            // case 1: NAME[j][x] = 0; break; // we have already read in NAME, but we need the ASCIIZ string terminator.
            case 2: GPA[j] = number; break;
        }
        // Are we at the end of line?
        if ((0x0a == c) || (0x0c == c)) {
            // Yes, break the cycle and read the next line
            break;
        }
        // Read the next field. Reinitialize number.
        field++;
        number = 0;
        // x = 0; // if we had another text field
        continue;
    }
    // Each time we get a digit, the old value of number is shifted one order of magnitude, and c gets added. This is called Horner's algorithm:
    // Number   Read    You get
    // 0        "1"     0*10+1 = 1
    // 1        "7"     1*10+7 = 17
    // 17       "2"     17*10+2 = 172
    // 172      ","     Finished. Store 172 in the appropriate place.
    if (c >= '0' && c <= '9') {
        number = number * 10 + (c - '0');
    }
    /*
       switch (field) {
           case 1:
               NAME[j][x++] = c; 
               break;
       }
    */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM