|
-
May 7th, 2007, 03:59 PM
#1
getline() and cin conflicts
Hi, I am writing a code that will put names into a map along with the ID numbers of the names (as in; John doe, ID: 23). In order to read the entire name I used the std::getline() function (since it jumps over spaces and terminates input on a new line) but when I get the ID I use a simple cin >> ID.
The problem arises when lower in my program I ask the user to input a name to search for in the database. Since this again can be more than one word I use a getline(), but when I run my program it skips over this step.
I thought this was iffy and when i changed the cin >> ID to a getline statement everything worked out. My question is; is there any way to have cin>> and getline() statements in your code without them compiling. I would really hate to have to write a stringToInto convertion function if i had to use a getline() to retrieve the ID number.
My code follows:
Code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class NameID
{
public:
string name;
string searchName;
int ID;
map<string, int> List;
map<string, int>::iterator iter;
//getInput fnc
//Reads input from user and puts data into std::map
void getInput()
{
cout << "Input into database.";
cout << endl;
cout << "Enter name and associated ID number.";
cout << endl;
cout << "A blank line ends input.";
cout << endl;
cout << endl;
cout << "Enter name: ";
getline(cin, name);
cout << "Enter ID #: ";
//getline(cin, ID);
cin >> ID;
cout << endl;
}
//puts item into map.
void putToMap()
{
List[name] = ID;
}
//findName fnc
//Searchs database for name and give name,ID pair.
void findName()
{
cout << "Enter name to search.";
cout << endl;
cout << "If name is stored in database, it will be printed out";
cout << endl;
cout << "along with the ID #.";
cout << endl;
cout << endl;
cout << "Enter name: ";
getline(cin,searchName);
cout << endl;
cout << "------Data Found-------";
cout << endl;
cout << List[searchName];
cout << endl;
}
};
//main fnc
//runs prog.
int main()
{
NameID Program;
Program.getInput();
Program.putToMap();
Program.findName();
//cout << Program.name;
//cout << Program.ID;
return 0;
}
Can anybody shed some light on this?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|