0

我不明白为什么atoi()除了第一个条目之外的每个条目都有效。我有以下代码来解析一个简单的 .csv 文件:

void ioReadSampleDataUsers(SocialNetwork *social, char *file) {
    FILE *fp = fopen(file, "r");

    if(!fp) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    char line[BUFSIZ], *word, *buffer, name[30], address[35];
    int ssn = 0, arg;

    while(fgets(line, BUFSIZ, fp)) {
        line[strlen(line) - 2] = '\0';

        buffer = line;
        arg = 1;

        do {
            word = strsep(&buffer, ";");

            if(word) {
                switch(arg) {
                    case 1:
                        printf("[%s] - (%d)\n", word, atoi(word));
                        ssn = atoi(word);
                        break;
                    case 2:
                        strcpy(name, word);
                        break;
                    case 3:
                        strcpy(address, word);
                        break;
                }

                arg++;
            }
        } while(word);

        userInsert(social, name, address, ssn);
    }

    fclose(fp);
}

.csv 示例文件是这样的:

900011000;Jon Yang;3761 N. 14th St
900011001;Eugene Huang;2243 W St.
900011002;Ruben Torres;5844 Linden Land
900011003;Christy Zhu;1825 Village Pl.
900011004;Elizabeth Johnson;7553 Harness Circle

但这是输出:

[900011000] - (0)
[900011001] - (900011001)
[900011002] - (900011002)
[900011003] - (900011003)
[900011004] - (900011004)

我究竟做错了什么?

4

2 回答 2

5

我猜你的 CSV 文件是以 UTF-8 格式保存的,并且在开头有一个 BOM(字节顺序标记atoi),这令人困惑。您可以通过在十六进制编辑器中查看文件或查看word.

UTF-8 的 BOM 是三个字节,其值为 0xEF、0xBB、0xBF。

如果可能,请将文件另存为 ASCII。如果没有,请添加代码以检测并跳过这些字节。

于 2010-04-07T16:47:59.343 回答
2

我的猜测是文件以字节顺序标记开头。atoi()将其视为非数字,因此返回 0。

if (line[0] == 0xEF && line[1] == 0xBB && line[2] == 0xBF) {
    /* byte order mark is present, so skip it somehow */
}
于 2010-04-07T16:48:19.380 回答