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.

Recommended Answers

All 2 Replies

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;
    }
}

I hate to be a bore, but Narue has written an extremely concise, in-depth post which is pinned at the top of this forum called How do I flush the input stream? - Please pay attention to sticky threads in future :-)

http://www.daniweb.com/forums/thread90228.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.