我正在尝试解析使用逗号作为delim的csv 我有几个字段在他们中使用逗号,但有他们周围的引号继承人我尝试n解析,但似乎每次都跳过if,即使使用以引号开头的测试数据?
// special case "run,fly,jump"
tokholder = strsep(&lineholder, ", \n");//gets next token of the line
//to handle special cases
printf("%c",tokholder[0]);
if (tokholder[0]=='"'){
char *temp = malloc(sizeof(tokholder)); /// to hold the value of tolk
strcpy(temp,tokholder);
tokholder = strsep(&lineholder, ", \n"); // gets next part of quoted comma seperated area
int lengtht = strlen(tokholder);
//checks for end quote loops untill it gets end quote in string
while(tokholder[lengtht-1]!='"'){
strncat(temp,tokholder,lengtht);
tokholder = strsep(&lineholder, ", \n");
}//end while
printf("outof special while");
strcpy(ptrtemp->movie_title, temp);
free(temp);
}//end if
我坚持尝试这个? 我必须在c
中写这个答案 0 :(得分:0)
有些问题可能是使用sizeof(tokholder)
产生指针的大小而不是字符串中的字符数。而是使用strlen ( tokholder)
始终添加一个用于终止'\0'
。在这种情况下,添加两个以允许将逗号或引号添加回字符串以及终止'\0'
。重新分配内存以允许内存,以便可以连接令牌。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void) {
char line[] = "\"run,fly,jump\",walk,sprint,leap";
char *lineholder = line;
char *tokholder = NULL;
tokholder = strsep(&lineholder, ", \n");//gets next token of the line
if ( tokholder) {
//to handle special cases
if ( tokholder[0] == '\"'){
char *temp = malloc ( strlen ( tokholder) + 2); // +2 for comma and '\0'
strcpy ( temp, tokholder);
strcat ( temp, ",");
//checks for end quote
if ( ( tokholder = strsep ( &lineholder, "\""))) {
int len = strlen ( temp) + strlen ( tokholder) + 2;//+2 for " and '\0'
char *cap = NULL;
if ( NULL == ( cap = realloc ( temp, len))) {
printf ( "problem realloc\n");
free ( temp);
return 0;
}
temp = cap;
strcat ( temp, tokholder);
strcat ( temp, "\"");//add the quote back
}//end while
if ( temp) {
printf ( "temp is %s\n", temp);
free ( temp);
}
if ( lineholder) {
printf ( "lineholder is %s\n", lineholder);
}
}//end if
}//end if
return 0;
}