所以我有一个.txt文件,如下所示:
** Paris ** Flight,5 days,visiting various monuments. | 2999.99 |
** Amsterdam ** By bus,7 days, local art gallery. | 999.99 |
** London ** Flight,3 days,lots of free time. | 1499.99 |
我希望将信息存储到3个变量,城市,描述和价格中,但我根本无法保存这些信息。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char city[256],desciption[256];
float temp;
if(fp=fopen("Ponuda.txt","rt")==NULL){
printf("ERROR\n");
exit(1);
}
while(fscanf(fp,"** %s ** %s | %f |",city,description,&temp)==3){
printf("** %s ** %s |%f|\n",city,description,temp);
}
return 0;
答案 0 :(得分:2)
IMO使用fgets
读取每个文件行要容易得多,然后使用strtok
用分隔符字符串"*|"
拆分每一行。
然后我使用strdup
将文本字符串复制到结构中,并使用sscanf
从第三个标记中提取票价。我应该测试strdup
的返回值,因为它在内部调用malloc
。
我还使用double
代替float
(我只会在有约束的情况下使用)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
typedef struct {
char *city;
char *descrip;
double fare;
} flight_t;
int main()
{
FILE *fp;
flight_t visit[MAX] = {0};
char buffer [1024];
char *tok;
int records = 0, i;
if((fp = fopen("Ponuda.txt", "rt")) == NULL) {
printf("Error opening file\n");
exit(1);
}
while(fgets(buffer, sizeof buffer, fp) != NULL) {
if((tok = strtok(buffer, "|*")) == NULL) {
break;
}
if(records >= MAX) {
printf("Too many records\n");
exit(1);
}
visit[records].city = strdup(tok); // add NULL error checking
if((tok = strtok(NULL, "|*")) == NULL) { // pass NULL this time
break;
}
visit[records].descrip = strdup(tok); // add NULL error checking
if((tok = strtok(NULL, "|*")) == NULL) { // pass NULL this time
break;
}
if(sscanf(tok, "%lf", &visit[records].fare) != 1) { // read a double
break;
}
records++;
}
fclose(fp);
// print the records
for(i = 0; i < records; i++) {
printf("** %s ** %s |%.2f|\n", visit[i].city, visit[i].descrip, visit[i].fare);
}
// free the memory given by strdup
for(i = 0; i < records; i++) {
free(visit[i].city);
free(visit[i].descrip);
}
return 0;
}
节目输出:
** Paris ** Flight,5 days,visiting various monuments. |2999.990000|
** Amsterdam ** By bus,7 days, local art gallery. |999.990000|
** London ** Flight,3 days,lots of free time. |1499.990000|
答案 1 :(得分:1)
使用单个fscanf语句非常困难,因为正如@Barmar指出的那样,城市名称可能不止一个单词。读取整行(使用fgets)然后自己解析行更容易。解析它: