你想要例如:
char restofline[64];
...
while(fscanf(fin, " %11[^ ]%44[^-]-%[^;]; %d.%d.%63[^\n]", taxi[i].code, taxi[i].from, taxi[i].to,
&taxi[i].day, &taxi[i].month, restofline)==6)
因为您需要刷新行的其余部分 scanf 不在您的代码中管理
注意第一个 '%' 之前的空格以绕过前一行的换行符,事实上我限制了要读取的字符串的大小以不写出数组
例如:
#include <stdio.h>
typedef struct{
char code[12];
char from[45];
char to[45];
int day;
int month;
int year;
int hour;
int min;
float km;
float price;
}Taxi;
int main()
{
int i = 0;
Taxi taxi[10];
char restofline[64];
while(fscanf(stdin, " %11[^ ]%44[^-]-%[^;]; %d.%d.%63[^\n]", taxi[i].code, taxi[i].from, taxi[i].to,
&taxi[i].day, &taxi[i].month, restofline)==6)
{
printf("|%s| |%s| |%s| |%d| \n", taxi[i].code, taxi[i].from, taxi[i].to, taxi[i].day);
if (++i == 10)
break;
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
CXKNS87356 John March 136 - Mary Perpetum 419; 8.2.2014. 05:42 3.80257 71.45
|CXKNS87356| | John March 136 | | Mary Perpetum 419| |8|
CXKNS87356 John March 136 - Mary Perpetum 419; 8.2.2014. 05:42 3.80257 71.45
|CXKNS87356| | John March 136 | | Mary Perpetum 419| |8|
^C
pi@raspberrypi:/tmp $
如果你想保存所有字段:
#include <stdio.h>
typedef struct{
char code[12];
char from[45];
char to[45];
int day;
int month;
int year;
int hour;
int min;
float km;
float price;
}Taxi;
int main()
{
int i = 0;
Taxi taxi[10];
while(fscanf(stdin, " %11[^ ] %44[^-]- %[^;]; %d.%d.%d.%d:%d%f%f",
taxi[i].code, taxi[i].from, taxi[i].to,
&taxi[i].day, &taxi[i].month, &taxi[i].year,
&taxi[i].hour, &taxi[i].min,
&taxi[i].km, &taxi[i].price)==10)
{
printf("|%s| |%s| |%s| |%d| %d:%d %f %f\n",
taxi[i].code, taxi[i].from, taxi[i].to, taxi[i].day,
taxi[i].hour, taxi[i].min, taxi[i].km, taxi[i].price);
if (++i == 10)
break;
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
CXKNS87356 John March 136 - Mary Perpetum 419; 8.2.2014. 05:42 3.80257 71.45
|CXKNS87356| |John March 136 | |Mary Perpetum 419| |8| 5:42 3.802570 71.449997
CXKNS87356 John March 136 - Mary Perpetum 419; 8.2.2014. 05:42 3.80257 71.45
|CXKNS87356| |John March 136 | |Mary Perpetum 419| |8| 5:42 3.802570 71.449997
^C
pi@raspberrypi:/tmp $
remark 在第一个 '%' 之前仍然存在的空格以绕过换行符从一行到下一行。我还在字段“to”的开头添加了一个以刷新空格,但您需要删除字段“from”和“to”末尾的可能空格