Reputation: 3
So what i am trying to do is basically get the second argument of a function, and making the second argument the name of a variable so i can easily store the users input. Here is my code
`
#pragma once
#include <iostream>
using namespace std;
void askAndStore(string question, string variable)
{
cout << question + " ";
cin >> variable;
}
`
Upvotes: 0
Views: 915
Reputation: 62704
You can't do this in C++.
You could have a std::map<std::string, SomeType>
that you populate with your read-in names.
#pragma once
#include <iostream>
#include <map>
#include <string>
class Values
{
std::map<std::string, std::string> values;
public:
void askAndStore(std::string question, std::string name)
{
std::cout << question << " ";
std::cin >> values[name];
}
std::string get(std::string name)
{
return values[name];
// or return values.at(name); if name must already exist in values
}
};
int main()
{
Values user;
user.askAndStore("What is your name?", "usersName");
}
That assumes your values are std::string
s
Upvotes: 1
Reputation: 36483
Pass variable by reference:
void askAndStore(string question, string& variable)
{
cout << question + " ";
cin >> variable;
}
string&
instead of string
. Without using &
you'd be passing in a copy of your varaible, using a reference type string&
you pass the actual variable in which is then modified by cin >> variable;
.
P.S Don't use using namespace std;
Upvotes: 3