【发布时间】:2020-10-16 00:09:20
【问题描述】:
基本上我需要从文件中读取输入,文件上的数据看起来像这样:
A422TCRE234VD3KJ349D;2000,Gasoleo;Vermelho,;17,200,Platinum;17,200,45;
3KJ349DA422TCRE234VD;,diesel;Azul,Minivan;17,200,45;10,20,30;
DA422TC3KJ349RE234VD;,;Vermelho,;,,;,,;
现在我需要做的是读取这些数据并用“;”分隔它我正在使用 sscanf,如下所示:
sscanf(line," %[^;];%[^;];%[^;];%[^;];%[^;]", campos[0],campos[1], campos[2] ,campos[3],campos[4]);
“line”变量保存从文件中读取的整行。到目前为止一切都很好。现在我需要将每个数组 (campos[x]) 拆分为 "," 因为我需要将每个数据保存在我创建的不同结构中。我试图通过使用一个辅助数组“输出”来实现这一点,其中我结合了所有以前的字段,如下所示:
strcpy(output,campos[1]);
strcat(output,",");
strcat(output,campos[2]);
strcat(output,",");
strcat(output,campos[3]);
strcat(output,",");
strcat(output,campos[4]);
然后我再次使用 sscanf 尝试拆分它们:
sscanf(output, " %[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]",helper[0],helper[1],helper[2],helper[3],helper[4],helper[5],helper[6],helper[7],helper[8], helper[9]);
但是虽然运气好,但它不起作用,可能是因为正如您在输入文件中看到的那样,某些属性是空的,问题是我需要它们保持空,因为之后我需要向用户显示数据与输入文件格式相同。
我尝试过使用strtok(),以及我这里的代码的许多变体,似乎没有任何效果。
为了让您有更好的想法,我将在这里写下我目前的输出:
puts(output); -> 2000,Gasoleo,Vermelho,,17,200,Platinum,17,200,45
,diesel,Azul,Minivan,17,200,45,10,20,30
,,Vermelho,,,,,,,
printf("%s,%s\n", helper[0],helper[1]); -> 2000,Gasole
,
,
另外我可以给出一个更好的视角,这个文件代表了一个汽车厂的工单,所以每一行如下:
Word Order Id;Horsepower,Fuel Type;Colour,Model;Diameter,Width,Colour;Diameter,Width,Height;
Example: Horsepower and Fuel Type are engine attributes, each ";" separates between car parts.
我可以尝试什么来解决这个问题?
【问题讨论】:
-
helper是如何声明的? -
嘿嘿,声明如下:char campos[12][32];字符助手[20][32];字符线[256];尽管我认为问题出在带有“,”的 sscanf 上。如果该行是“,XPTO”,他将无法正确进行拆分...