Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to bind a string to a function macro

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

本篇内容主要讲解"怎么将字符串与功能宏进行绑定",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"怎么将字符串与功能宏进行绑定"吧!

1 代码原理说明

利用switch和case的散转功能,宏作为散转条件,每一个宏对应一种功能,将宏和字符串进行绑定,这样通过比较字符串的方式,就能获得对应宏的功能代码。

此代码的好处是宏代码不用变的情况下,字符串和功能宏的对应是可以根据需要进行随意调整的。

代码结构清晰,易于维护。

2 实现源码

1)实现代码

一切说明,尽在注释中啦!代码可以理解为等级评定吧,实际意义不大,大家多关注这个小代码的结构吧!

#include #include // 功能宏散转编号 #define ONE_STAR 1 #define TWO_STAR 2 #define THREE_STAR 3 #define FOUR_STAR 4 #define FIVE_STAR 5 #define ZERO 0 // 无效输入返回值 /* 定义查找对应表结构及查找表数组 */ static struct lookuptable { char *str; // 指向字符串 int code; // 对应宏功能码 }tab[]= { // 字符串口与功能指示红的对应表,可以根据需要随意调整,下面的1-5可以换为任意字符串,只是输入时(查找时)也要一一对应上 {"1", ONE_STAR}, {"2", TWO_STAR}, {"3", THREE_STAR}, {"4", FOUR_STAR}, {"5", FIVE_STAR} }; // 查找函数声明 SearchFunc(char *s); int main(int argc, char *argv[]) { int score = 0; char str[10] = "\0"; printf("Please input number 1-5 to evaluate: "); gets(str); // 根据星级进行处理,这里就是简单的赋值,实际应用中可以根据需要更多 switch(SearchFunc(str)) { case ONE_STAR: { score += 1; break; } case TWO_STAR: { score += 2; break; } case THREE_STAR: { score += 3; break; } case FOUR_STAR: { score += 4; break; } case FIVE_STAR: { score += 5; break; } case ZERO: // 无效的情况,打印无效提升 { printf("\nYour input is invaild!\n"); break; } } // 输入有效才进行星级打印 if(SearchFunc(str)!=ZERO) { printf("\nThe score is: %d\n",score); } return 0; } /* 宏功能查找函数 */ SearchFunc(char *s) { int i; for(i=0; i

< sizeof(tab)/sizeof(tab[0]); i++) { if(strcmp(tab[i].str, s)==0) { return tab[i].code; } } return ZERO; // 输入不再范围内标记为0 } 2)运行结果 ① 输入值在有效范围1-5时,结果如下:

② When the input value is not within the valid range, the result is as follows:

At this point, I believe that everyone has a deeper understanding of "how to bind character strings with function macros," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report