Variables
I'm using VC+ 2010 Express. I didn't install anything else. I want to make console program which makes variable. Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
#include <string>
string varName
string varValue
int main () {
cout << "Write in variable's name" << endl;
cin >> varName;
cout << "Write in variable's value" << endl;
cin >> varValue;
var varName = varValue;
}
|
Is something like this possible?
If you don't understand what i sayed please ask a question.
No, that's not possible. C++ is not a reflexive language.
Why do you want to do this?
While it's not possible as described by the OP, it's fairly easy to approximate it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <string>
#include <cctype>
#include <map>
typedef std::map<std::string, std::string> map_type ;
bool continueAdding()
{
std::string answer ;
do
{
std::cout << "Continue entering variables? " ;
std::cin >> answer ;
} while ( answer.length()==0 ||
(!(std::tolower(answer[0]) == 'n' || std::tolower(answer[0]) == 'y')) );
return std::tolower(answer[0]) == 'y' ;
}
void addVars(map_type& vars)
{
std::string name, value ;
do
{
std::cout << "Variable's name: " ;
std::cin >> name ;
std::cout << name << "'s value: " ;
std::cin >> value ;
vars[name] = value ;
} while ( continueAdding() ) ;
}
void printVars(const map_type& vars)
{
map_type::const_iterator it = vars.cbegin() ;
while ( it != vars.cend() )
{
std::cout << it->first << ": " << it->second << '\n' ;
++it ;
}
}
int main()
{
map_type userVariables ;
addVars(userVariables) ;
printVars(userVariables) ;
}
|
Yeah, I was thinking of a map. That's why I asked the OP why they wanted to do this, to see if a map would be suitable.
Topic archived. No new replies allowed.