开发者

C++ User-Defined Vector

How do you declare a vector in c++ while allowing user input to define the vector's name? Okay, after reviewing your responses, here is more detail; Here is the error message from VS08 C++ console application -

Error 2 error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std::s开发者_StackOverflowtreamsize)' : cannot convert parameter 1 from 'std::istream' to 'char *' e:\c++\project 5\project 5\project 5.cpp 58 project 5

Here is the code:

void addRecord()
{
     vector<char>recordName;
     vector<inventory>recordNameUser;
     cout << "Name the record you want to store it as\n";
     cin.get(cin, recordName);
     cout << "Enter the item description\n";
     cin.get(cin, recordNameUser.itemDescription);
     cout << "Enter the quanity on hand\n";
     cin >> recordNameUser.quanityOnHand;
     cout << "Enter the wholesale cost\n";
     cin >> recordNameUser.wholesaleCost;
     cout << "Enter the retail cost\n";
     cin >> recordNameUser.retailCost;
     cout << "Enter the date of the inventory (mm/dd/yyyy)\n";
     cin >> recordNameUser.inventoryDate;
}


What are you really trying to do?

Normally, users don't care about the variable names. What you can do is store different vectors with different user defined keys:

map<string, vector<int> > user_vectors;
while (true) {
  string key = GetNameFromUserInput();
  int value = GetValueFromUserInput();
  user_vectors[key].push_back(value);
}

From your edited problem description, you really don't have a need for vectors at all.

map<string, inventory> inventory_map;
while (!done) {
  string item_name;
  cin >> item_name;
  inventory item;
  cin >> item.itemDescription;
  cin >> item.quantityOnHand;
  ...;
  inventory_map[item_name] = item;
}
for (map<string, inventory>::const_iterator it = inventory_map.begin();
     it != inventory_map.end(); ++it) {
   cout << "Inventory contains: " << it->first
        << " described as: " << it->second.description;
}


You want to have users give you a name and to be able to associate that with a vector of things? That's what a std::map is for, with a std::string as the key type and a std::vector as the payload type.


You mean you want the variable's name to be read from the user? You can't do that, and there isn't really a reason to; variable names only exist for the programmer's convenience; they don't even exist in the executable unless necessary

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜