第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在C中使用枚舉類型的變量作為字符串的簡(jiǎn)單方法?

在C中使用枚舉類型的變量作為字符串的簡(jiǎn)單方法?

C
犯罪嫌疑人X 2019-07-01 20:35:33
在C中使用枚舉類型的變量作為字符串的簡(jiǎn)單方法?我想做的是:typedef enum { ONE, TWO, THREE } Numbers;我正在嘗試編寫(xiě)一個(gè)函數(shù),它將執(zhí)行類似于以下情況的開(kāi)關(guān)情況:char num_str[10];int process_numbers_str(Numbers num) {   switch(num) {     case ONE:     case TWO:     case THREE:     {       strcpy(num_str, num); //some way to get the symbolic constant name in here?     } break;     default:       return 0; //no match   return 1;}與其在每一種情況下定義,是否有一種方法可以像我前面所做的那樣使用枚舉變量來(lái)設(shè)置它呢?
查看完整描述

3 回答

?
郎朗坤

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊

沒(méi)有內(nèi)置的解決方案。最簡(jiǎn)單的方法是使用char*其中枚舉的int值索引到包含該枚舉的描述性名稱的字符串。如果你有一個(gè)稀疏的enum(不從0開(kāi)始或在編號(hào)中有空白處),其中一些int映射足夠高,使得基于數(shù)組的映射不切實(shí)際,因此可以使用哈希表代替。


查看完整回答
反對(duì) 回復(fù) 2019-07-01
?
吃雞游戲

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊

// Define your enumeration like this (in say numbers.h);ENUM_BEGIN( Numbers )
    ENUM(ONE),
    ENUM(TWO),
    ENUM(FOUR)ENUM_END( Numbers )// The macros are defined in a more fundamental .h file (say defs.h);#define ENUM_BEGIN(typ) enum typ {#define ENUM(nam) nam#define ENUM_END(typ) };// Now in one and only one .c file, redefine the ENUM macros and reinclude//  the numbers.h file to build a string table#undef ENUM_BEGIN#undef ENUM#undef ENUM_END#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {#define ENUM(nam) #nam#define ENUM_END(typ) };#undef NUMBERS_H_INCLUDED   // whatever you need to do to enable reinclusion#include "numbers.h"// Now you can do exactly what you want to do, with no retyping, and for any//  number of enumerated types defined with the ENUM macro family//  Your code follows;char num_str[10];int process_numbers_str(Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO"
    } break;
    default:
      return 0; //no match
  return 1;}// Sweet no ? After being frustrated by this for years, I finally came up//  with this solution for my most recent project and plan to reuse the idea//  forever


查看完整回答
反對(duì) 回復(fù) 2019-07-01
  • 3 回答
  • 0 關(guān)注
  • 1088 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)