gpt4 book ai didi

c - 使用 strtok() 分解字符串并将其放入数组中

转载 作者:行者123 更新时间:2023-11-30 17:25:55 24 4
gpt4 key购买 nike

我正在编写一个基本程序,它接受 CSV 文件,打印第一个字段,并对其他字段进行一些数值评估。

我希望将所有数字字段放入​​一个数组中,但每次我这样做并尝试访问数组的随机元素时,它都会打印整个内容

我的 CSV 文件是:

Exp1,10,12,13
Exp2,15,16,19

我正在尝试访问第二个字段,以便打印

Exp1 12
Exp2 16

但是我得到了

Exp1 101213
Exp2 151619

如果有人可以提供一些建议。这是我的代码:

#define DELIM ","

int main(int argc, char *argv[])
{
if(argc == 2) {
FILE *txt_file;
txt_file = fopen(argv[1], "rt");

if(!txt_file) {
printf("File does not exist.\n");
return 1;
}

char tmp[4096];
char data[4096];
char expName[100];
char *tok;
int i;

while(1){
if(!fgets(tmp, sizeof(tmp), txt_file)) break;

//prints the experiment name
tok = strtok(tmp, DELIM);
strncpy(expName, tok, sizeof(expName));
printf("\n%s ", expName);

while(tok != NULL) {
tok = strtok(NULL, DELIM);

//puts data fields into an array
for(i=0; i < sizeof(data); i++) {
if(tok != NULL) {
data[i] = atoi(tok);
}
}
printf("%d", data[1]);
}
}
fclose(txt_file);
return 0;
}

最佳答案

要修复的示例

 char tmp[4096];
int data[2048];
char expName[100];
char *tok;
int i=0;

while(fgets(tmp, sizeof(tmp), txt_file)){
tok = strtok(tmp, DELIM);
strncpy(expName, tok, sizeof(expName));
printf("\n%s ", expName);

while((tok = strtok(NULL, DELIM))!=NULL){
data[i++] = atoi(tok);
}
printf("%d", data[1]);
i = 0;
}

关于c - 使用 strtok() 分解字符串并将其放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26945052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com