[英]Scan a line with spaces and symbols to separate the entries and using structures in 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;
然后,為每個聚會地點整齊地存儲所有東西。
所以,我要求一個 function 以我們之前看到的結構詢問和存儲所有信息(由“#”和“|”分隔)。 這個 function 是這樣的:
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 */
}
}
嘗試編譯並運行它。 此代碼應該拆分您的字符串。 您所要做的就是將結果正確地輸入到您的結構中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
/*Declare variable */
char *line = malloc(250 * sizeof(char *));
size_t line_size = 250;
char *argument = malloc(250 *sizeof(char *));
/*Get string and save it in line */
getline(&line,&line_size,stdin);
/*Split string */
char corrector[] = "#|\n";
argument = strtok(line,corrector);
while(argument != NULL){
printf("%s\n", argument);
argument = strtok(NULL,corrector);
}
return 0;
}
輸入:在我家#House#28#-134.943|47.293#21-24
Output:
In my house
House
28
-134.943
47.293
21-24
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.