我试图将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];
}
}
答案 0 :(得分:-1)
首先:对于您正在执行的操作,您可能需要仔细查看函数strtok
和atoi
宏。但是考虑到您发布的代码,这也许仍然有点太先进了,所以我在这里花了更长的时间。
假设该行类似于
172,924,1182
然后您需要解析这些数字。数字172实际上由内存中的两个或四个字节表示,格式非常不同,而字节“ 0”与数字0完全不同。您将看到ASCII码,十进制为48,或者十六进制为0x30。
如果将一个数字的ASCII值减去48,您将得到一个数字,因为幸运的是数字是按数字顺序存储的,因此“ 0”是48,“ 1”是49,依此类推。 / p>
但是您仍然存在将三个数字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;
}
*/
}