0

This code is supposed to get one int and one string.But after entering the int, the getline line is acting weird...it dont prompt me for any string input, rather then it shows the same value as the int.

#include<iostream>
#include<string>
using namespace std;

int main()
{
	int teacherID;
	string teacherName;

	cout << "Enter ID: ";
	cin >> teacherID;		
	cout << "Enter Name: ";
	getline(cin, teacherName);

	cout << teacherID << " " << teacherName << endl;

	return 0;
}

After i type 123 for int value following line appers:

Enter ID: 123
Enter Name: 123
Press any key to continue . . .

I think, i need to flush cin.But I dont find any flush method with cin.

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Bench
0

The ignore() method will flush cin, but it is better not to need to flush by always reading whole lines. :) Boost's lexical_cast<> makes it easy.

string teacherName;
int teacherID;
string line;

cout << "Enter ID: ";
getline(cin, line);
teacherID = lexical_cast<int>(line);
cout << "Enter Name: ";
getline(cin, teacherName);

If you do not want to install Boost, lexical_cast<> can be written with string streams.

#include <sstream>
#include <typeinfo>

namespace Ed {
template <typename Target, typename Source>
    Target lexical_cast(Source arg)
    {
        std::stringstream interpreter;
        Target result;

        if (!(interpreter << arg && interpreter >> result))
            throw std::bad_cast("Ed::lexical_cast<>");

        return result;
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.