![](/img/trans.png)
[英]c++ How do I print the value of a String attribute of a variable of another type?
[英]How do I get a variable to print a string
我的問題是,是否有辦法獲得一個整數變量,然后在設置時打印一個特定的單詞。
我的意思是,如果有人輸入值1
然后分配給變量int fCur
,有沒有辦法打印一個單詞(例如Germany
)而不是值1
?
cout << "You selected "<< fCur << endl;
我想要它打印
“你選擇了德國”
不
“你選擇了1”
我很抱歉這是我第一次使用這個網站
如果您希望將每個國家/地區編入索引,如下所示:
你可以簡單地使用這個:
#include <iostream>
#include <string>
int main()
{
std::string countries[] = {"Germany", "India", "Korea"};
int country_number;
std::cin >> country_number; // invalid input is not being checked
// array indexing starts from 0
std::cout << "You selected " << countries[country_number - 1] << std::endl;
return 0;
}
我建議使用枚舉來表示選項,並使用if語句來設置字符串值:
int main()
{
enum Country {GERMANY = 1, SPAIN = 2, ITALY = 3};
cout << "Enter an option: ";
int fCur{};
cin >> fCur;
string str;
if (fCur == GERMANY)
str = "Germany";
else if (fCur == SPAIN)
str = "Spain";
else if (fCur == ITALY)
str = "Italy";
else
;// Handle error
cout << "You selected " << str << endl;
}
我想你想創建一個菜單來選擇類似的選項 -
- 德國
- 我們
- 西班牙
- 中國等
如果僅分配給德國的整數1,則基於菜單使用switch
的選擇,if條件足以顯示
int n;
cin >> n;
switch(n) {
case 1: {
cout << "Germany" << endl;
break;
}
case 2: {
cout << "US" << endl;
break;
}
case 3: {
cout << "Spain" << endl;
break;
}
case 4: {
cout << "China" << endl;
break;
}
default: cout << "Select from valid set of options";
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.