简体   繁体   English

分组字符串数组C.

[英]Grouping array of Strings C

I have made an array of strings and I am trying to group a string array into categories. 我已经创建了一个字符串数组,我正在尝试将字符串数组分组。

So far my code looks like this: 到目前为止我的代码看起来像这样:

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

int
main(int argc, char *argv[]) {
    char *results[] = {"Canada", "Cycling", "Canada", "Swimming", "India", "Swimming", "New Mexico",
                       "Cycling", "New Mexico", "Cycling", "New Mecico", "Swimming"};



    int nelements, i, country_count;

    nelements = sizeof(results) / sizeof(results[0]);

    for (i = 0 ; i < nelements; i++) {
        printf("%s\n", results[i]);
    }

    return 0;
}

Which prints out this: 打印出来的是:

Canada
Cycling
Canada
Swimming
India
Swimming
New Mexico
Cycling
New Mexico
Cycling
New Mexico
Swimming

But I am trying to group the sports along with respective counts with the individual countries, which I want to look like this: 但是我想把各个国家的运动和各自的计数分组,我希望看起来像这样:

Canada
    Cycling  1
    Swimming 1

India
    Swimming 1

New Mexico
    Cycling  2
    Swimming 1

I am thinking of categorizing the countries with every i+2 element in the array, and using strcmp to remove the duplicate country strings, but I am not sure how to do this with the counts of the sports along with each country. 我正在考虑使用数组中的每个i+2元素对国家进行分类,并使用strcmp删除重复的国家/地区字符串,但我不确定如何使用每个国家/地区的运动计数来执行此操作。

I am just not sure how to go about this. 我只是不确定如何解决这个问题。 Any sort of help would be appreciated. 任何形式的帮助将不胜感激。

The solution depends on what kind of approach you want to take. 解决方案取决于您想采取何种方法。 Keeping a single character array (results* in your code) will not be to make your data dynamic. 保留单个字符数组(代码中的结果*)不会使您的数据动态化。 Essentially, you would want to use a dictionary data structure which stores (nested if required) pair. 基本上,您可能希望使用存储(如果需要,嵌套)对的字典数据结构。 In CI would have used structures in order to make it modular. 在CI中会使用结构来使其模块化。

First of all, You would need a structure to store sports and their counts(say medal count) 首先,您需要一个结构来存储运动及其数量(比如奖牌数量)

struct sport {
  char *sport_name;
  int medal_count;
  //Any other details you want to store
};

Then, a Country can play multiple sports. 然后,一个国家可以进行多项运动。 Hence we need to make country structure. 因此,我们需要建立国家结构。

struct Country{
  char *country_name;
  struct sport* results;
  //Any other details you want to store
};

Now let's create an array of country data. 现在让我们创建一个国家数据数组。

#define NO_OF_COUNTRIES 3  //You may fix this or make it dynamic
struct Country country_data[NO_OF_COUNTRIES]; 

You can fill data accordingly now. 您现在可以相应地填写数据。 Hope this helps. 希望这可以帮助。

Consider using a lists of cities and countries instead of an array of strings. 考虑使用城市和国家/地区列表而不是字符串数组。

The following code explain the simplest implementation with two structures and two methods for each - adding new element and searching element. 下面的代码解释了最简单的实现,其中包含两个结构和两个方法 - 添加新元素和搜索元素。

Try this code and then learn it: 试试这段代码,然后学习它:

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

struct city
{
    struct city * next;
    char * cityName;
    int counter;
};

struct country
{
    struct country * next;
    char * coutryName;
    struct city * cities;
};

struct country * findCountry(struct country * coutries, char * country)
{
    struct country * searchResult = NULL;
    while (coutries != NULL)
    {
        if (strcmp(country, coutries->coutryName) == 0)
        {
            searchResult = coutries;
            break;
        }
        coutries = coutries->next;
    }
    return searchResult;
}

struct country * addCountry(struct country * coutries, char * country)
{
    struct country * newCountry = malloc(sizeof(struct country));
    newCountry->next = coutries;
    newCountry->coutryName = country;
    newCountry->cities = NULL;
    return newCountry;
}

struct city * findCity(struct city * cities, char * city)
{
    struct city * searchResult = NULL;
    while (cities != NULL)
    {
        if (strcmp(city, cities->cityName) == 0)
        {
            searchResult = cities;
            break;
        }
        cities = cities->next;
    }
    return searchResult;
}

struct city * addCity(struct city * cities, char * city)
{
    struct city * newCity = malloc(sizeof(struct city));
    newCity->cityName = city;
    newCity->next = cities;
    newCity->counter = 0;
    return newCity;
}

int main(void) 
{
    char *results[] = { "Canada", "Cycling", "Canada", "Swimming", "India", "Swimming", "New Mexico",
        "Cycling", "New Mexico", "Cycling", "New Mexico", "Swimming" };

    struct country * countries = NULL;
    int nelements = sizeof(results) / sizeof(results[0]);
    // filling list of countries with sublists of cityes
    int i;
    for (i = 0; i < nelements; i+=2)
    {
        struct country * pCountry = findCountry(countries, results[i]);
        if (!pCountry)
        {
            countries = addCountry(countries, results[i]);
            pCountry = countries;
        }
        struct city * pCity = findCity(pCountry->cities, results[i+1]);
        if (!pCity)
        {
            pCountry->cities = addCity(pCountry->cities, results[i + 1]);
            pCity = pCountry->cities;
        }
        pCity->counter++;
    }

    // reading cities from all countries
    struct country * pCountry = countries;
    while (pCountry != NULL)
    {
        printf("%s\n",pCountry->coutryName);
        struct city * pCity = pCountry->cities;
        while (pCity != NULL)
        {
            printf("    %s %d\n", pCity->cityName, pCity->counter);
            pCity = pCity->next;
        }
        printf("\n");
        pCountry = pCountry->next;
    }

    return 0;
}

Note: in your code last "New Mexico" was like "New Mecico" , in my code this mistype was fixed. 注意:在你的代码中,最后一个"New Mexico"就像"New Mecico" ,在我的代码中,这个错误类型是固定的。

UPDATE UPDATE

Note 2: Because I add elements in the beginning of the lists order of countries and cities is reverse to order of their first mention in the source array. 注2:因为我在列表的开头添加元素,国家和城市的顺序与它们在源数组中首次提及的顺序相反。

If order is important you have two options: 如果订单很重要,您有两种选择:

1) rewrite my code to add new items to the end of list (it is the long way) 1)重写我的代码以将新项添加到列表的末尾(这是漫长的路)

2) rewrite for -loop in the main just to read initial array from the end (it is the easiest way): 2)在main重写for -loop只是为了从最后读取初始数组(这是最简单的方法):

// filling list of countries with sublists of cityes
int i;
for (i = nelements-2; i >=0 ; i -= 2)
   {
   . . .

I would use a struct (if you are not familiar, I always remind myself when needed with myStruct.c ) and with two arrays as data members, like this: 我会使用一个结构 (如果您不熟悉,我总是在需要时使用myStruct.c提醒自己)并使用两个数组作为数据成员,如下所示:

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

#define COUNTRY_LENGTH 15
#define MAX_SPORTS 5

enum sport_name { CYCLING, SWIMMING };

typedef struct Record {
  char country[COUNTRY_LENGTH];
  int sports[MAX_SPORTS];
} Record;

// return index of 'country' in 'array' if the 'country'
// is found inside 'array', else -1
int exists(char country[], Record* array, int size) {
    int i;
    for(i = 0; i < size; ++i)
        if(!strcmp(array[i].country, country))
            return i;
    return -1;
}

int find_sport_index(char sport[]) {
    if(!strcmp(sport, "Cycling"))
        return CYCLING;
    if(!strcmp(sport, "Swimming"))
        return SWIMMING;
    printf("I couldn't find a sport index for %s\n!!! Do something...Undefined Behavior!", sport);
    return -1;
}

char* find_sport_string(int sport) {
    if(sport == CYCLING)
        return "Cycling";
    if(sport == SWIMMING)
        return "Swimming";
    printf("I couldn't find a sport string for sport index %d\n!!! Do something...", sport);
    return NULL;
}

int main(int argc, char *argv[]) {
    // you had a typo, New Mecico, I corrected it..Also you could have used a struct here... ;)
    char *results[] = {"Canada", "Cycling", "Canada", "Swimming", "India", "Swimming", "New Mexico",
                       "Cycling", "New Mexico", "Cycling", "New Mexico", "Swimming"};



    int nelements, i, j;

    nelements = sizeof(results) / sizeof(results[0]);

    const int records_size = nelements/2;

    Record record[records_size];
    for(i = 0; i < records_size; i++) {
        for(j = 0; j < COUNTRY_LENGTH; j++) 
            record[i].country[j] = 0;
        for(j = 0; j < MAX_SPORTS; j++)
            record[i].sports[j] = 0;
    }

    int country_index, records_count = 0;
    for(i = 0; i < nelements; ++i) {
        // results[i] is a country
        if(i % 2 == 0) {
            country_index = exists(results[i], record, records_size);
            if(country_index == -1) {
                country_index = records_count++;
                strcpy(record[country_index].country, results[i]);
            }
        } else {
            // result[i] is a sport
            record[country_index].sports[find_sport_index(results[i])]++;
        }
    }    


    for(i = 0; i < records_size; ++i) {
        if(strlen(record[i].country)) {
            printf("%s\n", record[i].country);
            for(j = 0; j < MAX_SPORTS; j++) {
                if(record[i].sports[j] != 0) {
                    printf("    %s %d\n", find_sport_string(j), record[i].sports[j]);
                }
            }
        }    
    }

    return 0;
}

Output: 输出:

C02QT2UBFVH6-lm:~ gsamaras$ ./a.out 
Canada
    Cycling 1
    Swimming 1
India
    Swimming 1
New Mexico
    Cycling 2
    Swimming 1

The idea is that: 这个想法是:

  1. The struct Record holds the records in the Olympics, with relevant sports. 结构Record保存奥运会的记录,以及相关的运动。
  2. Record.country holds the name of the country (and I assume that it be 14 characters at max, +1 for the NULL terminator, thus I defined it as 15). Record.country保存国家的名称(我假设它最多为14个字符,NULL终止符为+1,因此我定义为15)。
  3. Record.sports is an array with size MAX_SPORTS - the size would be equal to all the sports in the Olympics, but I assumed it's 5. Every position of this array is a counter (of the medals every country got in a sport. For example, Record.sports[1] = 2 would indicate that this country has 2 medals in Swimming. But how I know it was Swimming? I decided apriori, as a programmer that the first counter is connected to Cycling, the second to Swimming and so on. I used an enum to make that more readable, instead of using magic numbers . (Note: You could use a list instead an array, but that would be an overkill for that application. But if you want to do it for fun (and because a bit less memory), you can use our List (C) ). Record.sports是一个大小为MAX_SPORTS的数组 - 大小将等于奥运会中的所有体育项目,但我认为它是5.该数组的每个位置都是一个计数器(每个国家参加体育运动的奖牌。例如, Record.sports[1] = 2表示这个国家在游泳中有2枚奖牌。但我怎么知道游泳?我决定先行,作为程序员,第一个计数器连接到Cycling,第二个是游泳,所以我使用enum来使它更具可读性,而不是使用魔术数字 。(注意:您可以使用列表而不是数组,但这对于该应用程序来说可能是一种过度杀伤。但是如果你想这样做是为了好玩(并且因为内存少了一点),你可以使用我们的List(C) )。
  4. You define results[] in a strange way, since you should really have used a struct for that, but I worked with your code...So I needed an array of Records , and its size should be equal to the number of the countries, ie the half of the size of results[] . 你以一种奇怪的方式定义results[] ,因为你应该真的使用了一个结构,但我使用了你的代码...所以我需要一个Records数组,它的大小应该等于国家的数量,即results[]大小的一半results[] Notice that because you defined results[] to contain implicit pairs of country-sport, a division by two is just enough to determine the size of the Record s array. 请注意,因为您定义results[]包含隐式的country-sport对,所以除以2就足以确定Record s数组的大小。
  5. I loop over results[] to populate record[] , by using a counter named i in the . 我通过在使用名为i的计数器来循环results[]以填充record[] When i is even, result[i] contains a country, else it contains a sport. i是偶数时, result[i]包含一个国家,否则它包含一项运动。 I use the module operator ( % ) to determine that easily. 我使用模块运算符( % )来轻松确定。
  6. If the country doesn't exist in record[] , then I insert it, else I don't insert it again. 如果record[]中不存在该国家/地区,则我将其插入,否则我不会再插入它。 In both cases I want to remember its index in record[] , so that in the next iteration, that we will process the sport, we will now at which position of record[] we should look into and act accordingly. 在这两种情况下,我都想记住它在record[]索引,因此在下一次迭代中,我们将处理这项运动,我们现在将在record[]哪个位置进行调查并采取相应的行动。
  7. Now, when I process a sport, I want to increase the counter of that sport, but only for the corresponding country (remember that I have stored the country index I had processed in the previous iteration). 现在,当我处理一项运动时,我想增加该运动的计数器,但仅限于相应的国家(请记住,我已经存储了我在上一次迭代中处理过的国家/地区索引)。
  8. Then I just print, that's it! 然后我就打印,就是这样! :) :)

Given you array I can see that country name is available alternatively. 鉴于你的数组,我可以看到国家名称可供选择。 If this is the format data is available in than you can follow the below code. 如果这是格式数据可用,您可以按照以下代码。

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

int main(int argc, char *argv[])
{
   char *results[] = {"Canada", "Cycling", "Canada", "Swimming", "India","Swimming", "New Mexico",
               "Cycling", "New Mexico", "Cycling", "New Mexico", "Swimming"};



   int nelements, i, sport_count=0,country_change =0;
   char country[50];char sport[50];
   strcpy(country,results[0]);
   printf("%s\n", country);
   strcpy(sport,results[1]);
   nelements = sizeof(results) / sizeof(results[0]);

   for (i = 1 ; i < nelements; i++) 
   {
      if(((i%2)==0) && (strcmp(country,results[i])))
      {
         //sport_count++;
         printf("\t%s %d\n", sport,sport_count);
         country_change =1;
         strcpy(country,results[i]);
         printf("%s\n", country);
      }
      else if((i%2)==1)
      {
          if(country_change)
          {
             strcpy(sport,results[i]);
             country_change = 0;
             sport_count = 0;
          }

          if(!strcmp(sport,results[i]))
          {
              sport_count++;
          }
          else
          {
              printf("\t%s %d\n", sport,sport_count);
              strcpy(sport,results[i]);
              sport_count = 1;
          }
             //strcpy(country,results[i]);
       }

    }
    printf("\t%s %d\n", sport,sport_count);

 return 0;
}

Basically this is what I am trying to do here: 基本上这就是我在这里要做的:

  1. Store the first index in a variable. 将第一个索引存储在变量中。
  2. Than in each even iteration check if the country name is equal to the stored name. 比在每个偶数迭代中检查国家名称是否等于存储的名称。 If not update the name. 如果没有更新名称。
  3. In each odd iteration you can just print out the name. 在每个奇数迭代中,您只需打印出名称即可。
  4. Sport name is stored in a variable and a int variable sports_count keeps the count. 运动名称存储在变量中,int变量sports_count保存计数。
  5. If new country arrives than print the name of sport first and than a mandatory update in the name of sport and relevant variables. 如果新国家到达,则首先打印运动名称,而不是以运动名称和相关变量进行强制更新。
  6. Last sport name is printed outside the loop. 最后的运动名称在循环外打印。

     Output Canada Cycling 1 Swimming 1 India Swimming 1 New Mexico Cycling 2 Swimming 1 

Idea of this solution is in building map - table where rows correspond to countries and columns correspond to sport events (or sport names). 这个解决方案的想法是建立地图表,其中行对应于国家,列对应于体育赛事(或体育名称)。

Memory for the maximum possible map (size is nelements/2 x nelements/2) is allocated with calloc but actually it can be just int[6][6] if char *results[] is unchanged. 最大可能映射的内存(大小是nelements / 2 x nelements / 2)是用calloc分配的,但实际上如果char *results[]不变则它可​​以只是int[6][6]

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

int main(void) 
{
    char *results[] = { "Canada", "Cycling", "Canada", "Swimming", "India", "Swimming", "New Mexico",
        "Cycling", "New Mexico", "Cycling", "New Mexico", "Swimming" };
    int nelements = sizeof(results) / sizeof(results[0]);
    int i;
    // making empty map
    int ** map = calloc(nelements/2, sizeof(int*));
    for (i = 0; i < nelements / 2; i++)
        map[i] = calloc(nelements/2, sizeof(int));
    char ** rowNames = calloc(nelements / 2, sizeof(char*));
    int usedRows = 0;
    char ** colNames = calloc(nelements / 2, sizeof(char*));
    int usedCols = 0;

    // filling the map
    // the outer loop for countries
    int c;
    for (c = 0; c < nelements; c+=2) {
        int row = -1;
        // Find country in the map (loop for rows)
        for (i = 0; i < usedRows; i++) 
        {
            if (strcmp(results[c], rowNames[i]) == 0)
            {
                row = i;
                break;
            }
        }
        // or add if it is new country
        if (row < 0)
        {
            row = usedRows;
            rowNames[usedRows] = results[c];
            usedRows++;
        }
        // Find sport in the map (loop for columns)
        int col = -1;
        for (i = 0; i < usedCols; i++)
        {
            if (strcmp(results[c+1], colNames[i]) == 0)
            {
                col = i;
                break;
            }
        }
        // or add if it is new sport
        if (col < 0)
        {
            col = usedCols;
            colNames[usedCols] = results[c+1];
            usedCols++;
        }
        // Just count sport event in the current country
        map[row][col]++;
    }

    // print results from map
    // the outer loop for countries (loop for rows in map)
    for (c = 0; c < usedRows; c++) {
        printf("%s\n", rowNames[c]);
        // the inner loop for sport
        for (i = 0; i < usedCols; i++)
            if (map[c][i])
                printf("   %s %d\n", colNames[i], map[c][i]);
        printf("\n");
    }

    return 0;
}

So when map , as well as rowNames (with countries) and colNames (with sports) are filled we can output data in any way. 因此,当map ,以及rowNames (带国家)和colNames (带运动)填充时,我们可以以任何方式输出数据。

There are a number of ways to approach this task, as you can see from the number of answers. 从答案的数量可以看出,有很多方法可以解决这个问题。 One element you will need, for either the countries, or the events (but not both), is a simple lookup table containing either country entries or event entries to allow you to distinguish whether the values in results are country names or event names. 对于国家/地区或事件(但不是两者),您将需要的一个元素是包含国家/地区条目或事件条目的简单查找表,以便您区分results中的值是国家/地区名称还是事件名称。 A simple country lookup (made global here, but could be function scope as well) such as the following works: 一个简单的国家查找(在这里制作全局,但也可以是函数范围),如下面的工作:

char *countries[] = { "Canada", "India", "New Mexico" }; /* countries lookup */

Another shortcut you can take is recognizing that the pointers within results have function scope as defined, so there is no need to copy or allocate memory to hold them -- they already exist in readonly memory. 您可以采用的另一个快捷方式是识别结果中的指针具有定义的函数作用域,因此不需要复制或分配内存来保存它们 - 它们已经存在于只读内存中。

One other struct element that helps is to keep a count of the events associated with the country, say eventcnt . 另一个eventcnt结构元素是保持与国家相关的事件的数量,例如eventcnt That can be incremented each time an event is added under the country. 每次在国家/地区下添加事件时,都可以增加。 You can use a country/events struct similar to: 您可以使用类似于以下内容的country / events结构:

typedef struct {
    char *country;
    char *event[MAXE];
    int eventcnt;
} host;

(the MAXE is a simple constant for the maximum events involved to allow you to use automatic storage with your array of structs. (it can easily be changed to allocate/reallocate storage on an as needed basis) MAXE是所涉及的最大事件的简单常量,允许您使用结构数组的自动存储。(可以根据需要轻松更改以分配/重新分配存储)

You then need to simply loop through the results array, once, understanding that events always follow the country before them. 然后,您需要简单地遍历results数组,一次,了解事件总是在它们之前跟随国家。 Using several nested loops keeps the number of times you traverse results to one-time. 使用多个嵌套循环可以将results遍历的次数保持为一次。 Essentially, you loop over each pointer in results , determine if it points to a country name, if it is a country name, then either add it if it doesn't exists as one of your host.country values, or skip it if it does (no need to updated pointers to point to the last occurrence of the country name) 基本上,你遍历results每个指针,确定它是否指向国家/地区名称,如果它是国家/地区名称,那么如果它不存在作为您的host.country值之一,则添加它,如果它不存在则跳过它是(不需要更新指针指向最后一次出现的国家/地区名称)

Since nested loops are involved, a simple goto provides all the control you need to determine when you are dealing with country names of when you are dealing with event names and allows you to take the action needed in each case. 由于涉及嵌套循环,因此简单的goto提供了在处理event名称时处理country名称所需的所有控件,并允许您在每种情况下采取所需的操作。

Then it is just a matter of printing/using the results you wanted which are now contained in a array of struct with hidx (host index) containing the total number of unique hosts involved. 然后,只需打印/使用您想要的结果,现在包含在带有hidx (主机索引)的struct数组中,其中包含所涉及的唯一主机的总数。

Putting the pieces together, you could do something similar to the following: 将各个部分放在一起,您可以执行类似以下操作:

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

/* constants max(countries, events) */
enum { MAXC = 8, MAXE = 16 };

char *countries[] = { "Canada", "India", "New Mexico" }; /* countries lookup */

typedef struct {
    char *country;
    char *event[MAXE];
    int eventcnt;
} host;

int main (void) {

    char *results[] = { "Canada", "Cycling", "Canada", "Swimming", 
                        "India", "Swimming", "New Mexico", "Cycling", 
                        "New Mexico", "Cycling", "New Mexico", "Swimming"};
    host hosts[MAXC] = {{ .country = NULL }};
    int hidx = 0, i, j, country_count, current = 0, nelements;

    country_count = sizeof countries/sizeof *countries;
    nelements = sizeof results / sizeof *results;

    for (i = 0 ; i < nelements; i++) {          /* for each element */
        for (j = 0; j < country_count; j++) {   /* check if country */
            if (strcmp (results[i], countries[j]) == 0) { /* if so */
                int k;
                for (k = 0; k < hidx &&  /* check if already assigned */
                    strcmp (hosts[k].country, countries[j]); k++) {}
                if (!hosts[k].country) { /* if not, assign ptr, increment */
                    hosts[hidx++].country = results[i];
                    current = hidx - 1;;
                }
                goto nextc; /* skip event adding */
            }
        } /* results[i] is not a country, check if event exists for host */
        if (hosts[current].eventcnt < MAXE) {   /* if it doesn't, add it */
            int k;
            for (k = 0; k < hosts[current].eventcnt; k++)
                if (strcmp (results[i], hosts[current].event[k]) == 0)
                    goto nextc;  /* already exists for host, skip add */
            hosts[current].event[hosts[current].eventcnt++] = results[i];
        }
        nextc:;
    }

    for (i = 0; i < hidx; i++) {    /* output countries & events for each */
        printf (" %s\n", hosts[i].country);
        for (j = 0; j < hosts[i].eventcnt; j++)
            printf ("     %s\n", hosts[i].event[j]);
    }

    return 0;
}

Example Use/Output 示例使用/输出

$ ./bin/events
 Canada
     Cycling
     Swimming
 India
     Swimming
 New Mexico
     Cycling
     Swimming

Look over all the answers. 查看所有答案。 There are many good points contained. 包含许多好处。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。

I would enumerate both the sports and the locations, adding NUM_ x as the last element, so the enumerations can be easily appended in the future... 我会枚举运动和位置,添加NUM_ x作为最后一个元素,因此将来可以轻松添加枚举...

typedef enum _sport_t
{
  CYCLING,
  SWIMMING,
  NUM_SPORTS
} sport_t;

typedef enum _location_t
{
  CANADA,
  INDIA,
  NEW_MEXICO,
  NUM_LOCATIONS
} location_t;

Now, you can define string arrays to use when you want to print out the names... 现在,您可以定义要在打印名称时使用的字符串数组...

char* sports_name[NUM_SPORTS] = {"Cycling", "Swimming"};
char* location_name[NUM_LOCATIONS] = {"Canada", "India", "New Mexico"};

This approach will reduce your storage a bit and increase efficiency since you will be comparing enumerations (integers) instead of strings when you categorize the list. 这种方法会减少存储空间并提高效率,因为在对列表进行分类时,您将比较枚举(整数)而不是字符串。

You might also want to consider using a two dimensional boolean array of all locations and all sports, indicating whether said location has said sport. 您可能还想考虑使用所有位置和所有运动的二维布尔数组,指示所述位置是否具有所述运动。

typedef enum _bool_t
{
  FALSE,
  TRUE
} bool_t;

bool_t sports_array[NUM_LOCATIONS][NUM_SPORTS] =
{ 
  {TRUE,TRUE},  // Canada
  {TRUE,FALSE}, // India
  {TRUE,TRUE},  // New Mexico
};

So, your loops would look like this... 所以,你的循环看起来像这样......

location_t l;
sport_t s;

for (l = (location_t)0; l < NUM_LOCATIONS; l++)
{
  printf( " %s\n", location_name[l] );
  for (s = (sport_t)0; s < NUM_SPORTS; s++)
  {
    if (sports_array[l,s])
    {
      printf( "     %s\n", sport_name[s] );
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM