首页 > 解决方案 > 如何存储字符串直到找到空格

问题描述

我需要制作一个程序来检查文件中的城市名称是否在另一个文件中。文件 city.txt 类似于:

伦敦(2 位)巴黎(3 位)巴塞罗那(3 位)迈阿密(2 位)东京(2 位)柏林(3 位)曼彻斯特(3 位)罗马(2 位)悉尼

文件 ckeck_cities.text 就像:

巴塞罗那 迈阿密 东京 悉尼

我将文件 check_cities.txt 存储到一个结构中,我知道我需要为 city.txt 编写一个循环,该循环通过搜索空格来查找单词边界,然后将每个单词与整个第二个城市列表 (check_cities.txt) 进行比较。

问题是我不知道如何在找到空格后存储字符串。谁能告诉我我该怎么做?

'''

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>

    #define MAX_SIZE_NAME_CITY 10
    #define NUMB_CITIES 20
    #define MAX_STRING_SIZE 100

    FILE *fp;

    typedef struct {
            char checkcities[MAX_SIZE_NAME_CITY];
        }listn;
        listn n[NUMB_CITIES];

    void process(const char *city) {
    int i=0, j=0;

    while(i<strlen(city)-1){ //read all lines
            for ( i = 0; fscanf(fp, "%s", city[i]) == 1; ++i);

            while ((strcmp(city,n[j].checkcities)!=0)&& (j<NUMB_CITIES)){
                    j++;
            }
            if (strcmp(city,n[j].checkcities.)==0){
                printf("%s", n[j].checkcities);
                i++;
            }
            j=0;
    }
}

    int main()
    {
        int i=0;

        FILE *arch;

        arch = fopen("check_cities.txt", "r");

        if (arch==NULL){
            printf("ERROR");
        }
        else{
            while (!feof(arch)){
                fscanf(arch, "%s\n", n[i].checkcities);
                i++;
                // store the names into the struct
            }
        }
        fclose(arch);


        char city[MAX_SIZE_NAME_CITY];
        fp = fopen("cities.txt", "r");
        if (fp==NULL){
            printf("ERROR");
        }while (fgets(city, MAX_SIZE_NAME_CITY,fp) != NULL){
        process(city);}
        fclose(fp);

        return 0;
    }

'''

标签: cstring

解决方案


推荐阅读