0

I have a problem. I want to create an integer by user input. For example:

#include <iostream>
#include <string>
 
using namespace std;

int main()
{
    int i = 0;
    char newVar;
    string newVarName;
    cout << "New Variable? (y/n)" << endl;
    cin >> newVar;
    if (newVar == 'y') {
        /* newVarName declares new int with the name
        of the user input (newVarName = test --> int test)*/
    } else {
        break;
    }
    return 0;
}

How can I do this?

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
felix.lnz
  • 29
  • 1

2 Answers2

3

As @Fantastic Mr Fox mentioned :

int name_dependant_on_user_input = value_from_user

This is impossible in c++, because the variable name, is a compile time thing. The user input happens at runtime, which is after compilation has completed. Something you could do, is map a string input to your user input, for eg.

Some other error: String should be string or std::string. And using break; while not within loop or switch statements will return an error. If you want to escape immidiately, you could use exit(0);

Otherwise, as @Eljay mentioned above, a map<string, int> can be used to store both the name and value of your variable:

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main()
{
    char newVar;
    string newVarName;
    map<string, int> varName;
    cout << "New Variable? (y/n) : ";
    cin >> newVar;

    if (newVar == 'y') {
        cout << "Name : "; cin >> newVarName;
        cout << "Int : "; cin >> varName[newVarName];
    } else {
        exit(0);
    }

    //testing
    cout << "Test : " << newVarName << " = " << varName[newVarName];

    return 0;
}

Result:

New Variable? (y/n) : y
Name : var
Int : 5
Test : var = 5

Also, see why using namespace std; is considered a bad practice.

More info:

2

In c++, you need to be aware of the common concepts of compile time and run time. So in your example:

// newVarName declares new int with the name of the user input

If you mean something like this:

int name_dependant_on_user_input = value_from_user

This is impossible in c++, because the variable name, is a compile time thing. The user input happens at runtime, which is after compilation has completed. Something you could do, is map a string input to your user input, for eg.

std::unordered_map<std::string, int> user_vars;
std::string variable_name;
int variable_value;

cin >> variable_name;
cin >> variable_value;
user_vars[variable_name] = variable_value;

...

for (const auto& value_pair : user_Vars) {
    std::cout << "User value for " << value_pair.first << " is " << value_pair.second;
}
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175