Reputation: 77
My question is if there was a way to get an integer variable and then print a specific word when it is set.
What I mean is if someone inputs a value of 1
that is then assigned to variable int fCur
, is there a way to print a word (for example Germany
) instead of the value 1
?
cout << "You selected "<< fCur << endl;
I want it to print
"You selected Germany"
not
"You selected 1"
I appologize if this is poorly worded this is my first time using this site
Upvotes: 1
Views: 104
Reputation: 36
If you want to have each country indexed as follows:
you can simply use this:
#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;
}
Upvotes: 2
Reputation: 10998
I suggest using an enum to represent the options, and to use if statements that will set the string value:
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;
}
Upvotes: 1
Reputation: 298
As I guess it you want to create a menu for selecting options something like -
- Germany
- US
- Spain
- China etc
If it is only integer 1 that is assigned to Germany then an if condition is enough else to display based on the selection from a menu use switch
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";
}
Hope this helps.
Upvotes: 0