如何声明一个包含键和值的数组作为字符串,一个键可以有多个值?

时间:2014-04-08 01:24:50

标签: c arrays pointers

我正在练习C编程练习,要求编写一个模拟短消息服务(SMS)的程序。该程序允许用户输入缩写字符串,如" IMO",然后显示一些全文;例如,"在我看来","国际海事组织"和"以纪念"。我正在考虑声明一个存储键和值的数组,但我不知道如何创建一个键来保存多个值。我也想硬编码短信字典,键数和值的数量,以及他们的长度不固定。

我的程序中已经有了这一行,但它并不能满足我的期望。

char *dictionary[10][2]; // this code can only keep 10 keys and 10 values, and the length is defined to 10 characters.

1 个答案:

答案 0 :(得分:0)

我不知道为什么包含strcmp()的行不会为2个相等的字符串返回0。

#include <stdio.h>
#include <string.h>
#define DATAINPUTSIZE 180
#define STRUCTSIZE 10

struct TextStruct
{
    char * key;
    char * values;
    struct TextStruct *next;
};

typedef struct TextStruct TextStruct;

int main(void)
{
    size_t i;
    char *tokenPtr; // create char pointer
    char data_input[DATAINPUTSIZE];
    TextStruct sms1, sms2, sms3, sms4, sms5, sms6, sms7, sms8, sms9, sms10;
    TextStruct smsCases[] = 
    {
        {"AFAIK", "As far as I know", &sms1},
        {"AFK", "Away from keyboard", &sms2},
        {"LUV", "Love", &sms3},
        {"THX", "Thanks", &sms4},
        {"2day", "Today", &sms5},
        {"B4", "Before", &sms6},
        {"HAND", "Have a nice day", &sms7},
        {"CU", "See you", &sms8},
        {"SWYP?", "So what's your problem", &sms9},
        {"hh", "Haha", &sms10}
    };

    // Gets user's input
    puts("Enter a SMS (180 charaters exclusive): ");
    fgets(data_input,DATAINPUTSIZE,stdin);

    // Prints the string of data_input
    puts(data_input);

    // Tokenize the space characters; Compare each word if it is equal to keys (shortcut) of each struct
    // Tokenizing sentence
    tokenPtr = strtok(data_input, " ");

    // continue tokenizing sentence until tokenPtr becomes NULL
    while (tokenPtr != NULL)
    {
        //printf("%s\n", tokenPtr);
        for (i = 0; i < STRUCTSIZE; ++i)
        {
            if(strcmp(tokenPtr, smsCases[i].key) == 0)
            {
                puts(smsCases[i].values);
            }
        }
        tokenPtr = strtok(NULL, " "); // get next token
    }

    return 0;
}