簡體   English   中英

Fscanf讀取c語言中float和character的混合

[英]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)然后自己解析該行要容易得多。 要解析它:

  1. 在“ **”之后找到第一個非空白字符
  2. 找到此后的最后一個非空白字符,該字符之前應為“ **”
  3. 這些索引之間的文本將是城市名稱(可能包含空格)
  4. 描述是在步驟2中找到的“ **”和下一個“ |”的索引之間的文本。 之后。
  5. 成本是“ |”之后的字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM