我有一个包含数据的文件,以下是数据示例:
S:BMW;328i;A8;2.0
S:GMC;K1500 SIERRA 4X4;A4;5.3
C:SUBCOMPACT;M5;X
C:PICKUP TRUCK;A4;X
我想扫描行上的第一个字符并将数据存储在
A
如果A是一个
'S'
,我想将剩余的数据存储在B
,C
,D
,E
如果A是一个
'C'
,我想将剩余的数据存储在F
,G
,H
如何对文件中的每一行执行此操作?
这是我为另一个文件所做的,其中每一行都有相同的格式:
int currentSize = 0;
while(fscanf(fp, "%d,%[^,],%[^,],%[^,],%f,%[^,],%c,%f,%f,%f,%f", &data[currentSize].year, &data[currentSize].make, &data[currentSize].model,
&data[currentSize].type, &data[currentSize].engineSize, &data[currentSize].transmissionType, &data[currentSize].fuelType, &data[currentSize].city,
&data[currentSize].hwy, &data[currentSize].fuelPerYear, &data[currentSize].co2) != EOF) {
currentSize++;
}
return currentSize;
最佳答案
您可以使用fgets()
获取每行的内容,然后根据第一个字符使用sscanf()
获取每个字段:
char line[MAX_CHAR];
while (fgets(line, sizeof line, fp) != NULL)
{
switch(line[0])
{
case 'S':
//process line using sscanf()
break;
case 'C':
//process line using sscanf()
break;
//...
}
}