c - 用空格和符号扫描一行以分隔条目并使用 C 中的结构
问题描述
所以这段代码的目的是扫描这样一个句子:
在我家#House#28#-134.943|47.293#21-24
该代码必须扫描由“#”分隔的 6 个不同部分。第一个,“在我家”是聚会的地点,第二个“房子”是聚会的地点类型,第三个“28”是到达那里的步行时间,第四个“-134.943|47.293”是用“|”分隔的经纬度(查找地点),最后,“21-24”是聚会开始和结束的时间。所有前面的参数都必须保存在不同的变量中,这些变量的结构如下所示:
typedef struct {
char name[MAX]; //name of the location
char location_type[MAX]; //type of location
int travel; //time to arrive
int latitude;
int longitude;
int hours[5]; //when the party starts and ends
} Locations;
然后,为每个聚会地点整齐地存储所有东西。
所以,我要求一个函数来询问和存储我们之前看到的结构中的所有信息(由“#”和“|”分隔)。这个函数是这样的:
int AddLocation(Locations location[]) {
int i = 0;
i = num_locations;
printf ("Location information: ");
// here should be the scanf and this stuff
i++;
return i;
}
解决方案
对格式进行一些更改(即,lat/long 需要是浮点数,我不确定您对 int 数组的用途hours
是什么),您可以执行以下操作:
#include <stdio.h>
#define MAX 32
struct loc {
char name[MAX];
char location_type[MAX];
int travel;
float latitude;
float longitude;
char hours[MAX];
};
int
main(void)
{
struct loc Locations[16];
struct loc *t = Locations;
struct loc *e = Locations + sizeof Locations / sizeof *Locations;
char nl;
char fmt[128];
/* Construct fmt string like: %31[^#]#%31[^#]#%d#%f|%f#%31[^\n]%c */
snprintf(fmt, sizeof fmt,
"%%%1$d[^#]#%%%1$d[^#]#%%d#%%f|%%f#%%%1$d[^\n]%%c", MAX - 1);
while( t < e
&& 7 == scanf(fmt,
t->name, t->location_type, &t->travel,
&t->latitude, &t->longitude, t->hours, &nl
) && nl == '\n'
) {
t += 1;
}
for( e = Locations; e < t; e++ ){
; /* Do something with a location */
}
}
推荐阅读
- javascript - 有没有办法自定义嵌入在 SharePoint 现代网站模板中的 WebChat 机器人?
- javascript - 为什么会出现此错误:错误:连接 ECONNREFUSED?
- sql - 文本列的 SQL Pivot
- vue.js - 绘制画布大小时画布大小不同
- excel - 计算(不列出!)范围内的唯一项目以分配给变量
- c++ - 通过 const 引用传递时修改对象
- javascript - 在使用 jquery 的视图内进行按钮检查之前调用事件
- flutter - 如何在 Flutter 中使用 graphql 在 Mutation 中传递枚举?
- c# - 命令“esriRegasm.exe ...”以代码-1 退出。我无法构建项目
- c - 在 C 上不使用数组对整数进行排序