本文介紹了如何將枚舉類型變量轉換為字符串?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何讓 printf 顯示枚舉類型變量的值?例如:
How to make printf to show the values of variables which are of an enum type? For instance:
typedef enum {Linux, Apple, Windows} OS_type;
OS_type myOS = Linux;
而我需要的是類似
printenum(OS_type, "My OS is %s", myOS);
必須顯示字符串Linux",而不是整數.
which must show a string "Linux", not an integer.
我想,首先我必須創建一個值索引的字符串數組.但我不知道這是否是最美麗的方式.有可能嗎?
I suppose, first I have to create a value-indexed array of strings. But I don't know if that is the most beautiful way to do it. Is it possible at all?
推薦答案
確實沒有什么漂亮的方法可以做到這一點.只需設置一個由枚舉索引的字符串數組即可.
There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.
如果你做很多輸出,你可以定義一個操作符<<它接受一個枚舉參數并為您進行查找.
If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.
這篇關于如何將枚舉類型變量轉換為字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!