[英]Fscanf to read a mixture of float and characters in c
所以我有一個.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;
在IMO中,使用fgets
讀取每個文件行要容易得多,然后使用strtok
用分隔符字符串"*|"
分隔每一行。 。
然后,我使用strdup
將文本字符串復制到struct中,並使用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|
用單個fscanf語句很難做到這一點,因為正如@Barmar指出的那樣,城市名稱可能超過一個單詞。 閱讀整行(使用fgets)然后自己解析該行要容易得多。 要解析它:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.