c++ - How can you initialize an object from a variables value? -
i generate name of initialized object getting user input. possible? there way name object based on variables value?
i know in code below "test x" doesn't work , know why... there way work? have been trying figure out 2 days now. closest thing came maybe stringstreams... or worse... isn't possible? help?
#include <iostream> using namespace std; #include <string> class test { public: string wtf; }; int main() { test y; // showing normal initialize y.wtf = "a"; // assign value string x; cin >> x; // initialize string , input test x // trying initialize object based on input x.wtf = "a"; // assign value cout << y.wtf; // printing both test cout << x.wtf; return 0; }
my intent have single array holds employee numbers (concatenated "emp" or in beginning) initiate objects each employee. user input employee number, 1234, , make string added emp + 1234 , come out "emp1234"... initiate object "test emp1234" have bunch of difference variables associated it, inside class.
i may looking @ wrong... , explained crappy. new this, use possible.
i this:
#include <vector> #include <string> #include <iostream> #include <stdexcept> test make_test() { std::string s; if (!(std::cin >> s)) { throw std::runtime_error("premature end of input"); } return { "emp" + s }; } int main() { std::vector<test> v; (int = 0; != 10; ++i) { v.push_back(make_test()); std::cout << "added employee '" << v.back().wtf << "'\n"; } }
this fill vector ten employee records.
Comments
Post a Comment