Friday, July 31, 2009

How can I grab user input using cin in C++ then take that and create a string with that name?

I am making a program for storing contact data for an assignment and need to know how I can make the string's name the same thing the user input. This is not for school :).

How can I grab user input using cin in C++ then take that and create a string with that name?
As far as I know there is no way of doing that directly, however, here is an idea of accomplishing a similar thing:





C++ has a data type (a thing to store data -- like an int, double, string, etc.) called a "hash map" (some people call it a "hash table", too, both are correct). It stores things in pairs of "key"s and "value"s. Some example keys and values for your program might be:





KEY (name) / VALUE (age):


Bob / 16


Sally / 17


Bill / 40





To create a hash table, first include the proper library for it (#include %26lt;map%26gt; where you include everything else such as iostream or string, etc.), and then somewhere in your program, declare it in the following way:





map%26lt;string, int%26gt; my_hash_map;





This creates a new map variable named "my_hash_map" which has strings for keys and ints for values (as in our example with names and ages).





To add a person and their age to the map, do the following:





my_hash_map["Bob"] = 16;


my_hash_map["Sally"] = 17;


my_hash_map["Bill"] = 40;





When you want to look up someone's age, you can do the following (prints "Bob's age is 16; Sally's age is 17; Bill's age is 40"):





cout %26lt;%26lt; "Bob's age is " %26lt;%26lt; my_hash_map["Bob"] %26lt;%26lt; "; Sally's age is " %26lt;%26lt; my_hash_map["Sally"] %26lt;%26lt; "; Bill's age is " %26lt;%26lt; my_hash_map["Bill"] %26lt;%26lt; endl;





You can find more information on hash maps including how to delete items at it's C++ Reference page: http://www.cplusplus.com/reference/stl/m... .


No comments:

Post a Comment