1

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

1
  • 2
    You can use string in C++ for this purpose. string str; if(fCur==1)str="Germany"; Commented Jun 27, 2015 at 12:47

3 Answers 3

2

If you want to have each country indexed as follows:

  1. Germany
  2. India
  3. Korea

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

What for is the switch?
What do you mean by 'optional' on break statement? Removing them would be atrociously wrong!
1

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;
}

Comments

0

As I guess it you want to create a menu for selecting options something like -

  1. Germany
  2. US
  3. Spain
  4. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.