C 如何扫描文件并根据行的第一个字符将数据存储在不同的变量中?
我有一个包含数据的文件,以下是数据示例: 我想扫描行中的第一个字符,并将数据存储在C 如何扫描文件并根据行的第一个字符将数据存储在不同的变量中?,c,file,scanf,C,File,Scanf,我有一个包含数据的文件,以下是数据示例: 我想扫描行中的第一个字符,并将数据存储在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
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;
//...
}
}
考虑只取第一个字母,然后用separate
fscanf
s取其余字母:
// notice the space behind %c
while ( fscanf( " %c", &A ) == 1 ) {
if ( A == 'S' && fscanf( ":%[^;];%[^;];%[^;];%f", B, C, D, &E ) == 4 ) {
// do whatever with them
}
if ( A == 'C' && fscanf( ":%[^;];%[^;];%c", F, G, &H ) == 3 ) {
// do whatever with them
}
当逻辑and运算符
&&
的第一个操作数错误时,第二个操作数被定义为not get运算符。谢谢。我会给你一个机会try@user3211391注意:确保根据应扫描的预期字段数而不是“!”=EOF`。
// notice the space behind %c
while ( fscanf( " %c", &A ) == 1 ) {
if ( A == 'S' && fscanf( ":%[^;];%[^;];%[^;];%f", B, C, D, &E ) == 4 ) {
// do whatever with them
}
if ( A == 'C' && fscanf( ":%[^;];%[^;];%c", F, G, &H ) == 3 ) {
// do whatever with them
}