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

标签 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.

最佳答案

我不知道为什么包含 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;
}

关于c - 如何声明一个包含键和值作为字符串的数组,并且一个键可以有多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22925980/

相关文章:

c - 打开不带扩展名的文件

c - 如何不忽略 dyld 的最大版本

c - ELLCC 嵌入式 LLVM 编译失败,某些 asm 指令针对 Thumb2 Cortex-M0

c - 将一个命令 (execv) 的输出发送到另一个命令

c# - "1 item from each of N collections"的每个组合

perl - 如何使用 Win32 :API? 将指针传递给 DLL

java - 使用递归解决二维数组迷宫

c++ - 我必须从头开始吗?

c++ - 复制构造函数中的 std::copy 出错

c++ - 如何在 C++ 中通过引用传递指针