gpt4 book ai didi

c - Fscanf 读取 c 中 float 和字符的混合

转载 作者:行者123 更新时间:2023-12-04 02:11:00 27 4
gpt4 key购买 nike

所以我有一个 .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 将文本字符串复制到结构中,并使用 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|

关于c - Fscanf 读取 c 中 float 和字符的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38379915/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com