gpt4 book ai didi

c - 如何在 C 中解析带引号的 .csv 文件

转载 作者:行者123 更新时间:2023-11-30 16:22:22 26 4
gpt4 key购买 nike

假设我尝试解析的字符串读取

"Smith, John",Data1,Data2,Data3

我还可以得到读取的行

Dave, Data1,Data2,Data3

所以我有 if 语句

line 是文件中的文本行 fgets(),但我认为这有效

剩下的事情我已经挣扎了大约一个小时左右。我正在尝试重新格式化“Smith,John”,使其成为 John Smith,然后将其分配给 recTemp.artist

if (line[0] == '\"') {
//Read the last name, first name",
char lastTemp[30] = "";
char firstTemp[30] = "";
strcpy(lastTemp , strtok(line, ", "));
strcpy(firstTemp, strtok(NULL, "\","));
char * t;
t = strstr(lastTemp, "\"");
strcpy(t, " ");
//Concatenate each string assign to the artist value
strcat(firstTemp, lastTemp);
strcpy(recTemp.artist, firstTemp);
}

我认为错误来自 strstr 调用或紧随其后的 strcpy,但我不确定

谢谢!

最佳答案

回答您的问题:

"I'm trying to reformat the "Smith, John" so its John Smith"

如果不使用正则表达式从字符串中提取引号,我会执行以下操作,

#include <iostream>
#include <cstring>
#include <stdio.h>

int main() {
char line[100] = "\"Smith,John\",Data1,Data2,Data3";
// fgets(line, 100, stdin);
char* name = strtok(line, "\"");
char *substring2 = strtok(NULL, "\"");
char* LastName = strtok(name, ",");
char* FirstName = strtok(NULL, ",");

char result[100];
strcpy(result, FirstName);
strcat(result, ",");
strcat(result, LastName);
strcat(result, substring2);
printf("%s",result);

}

产生输出:

John,Smith,Data1,Data2,Data3

关于c - 如何在 C 中解析带引号的 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474206/

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