Hello programmers!
I am having a function that has the user enter a name for an object, check if its valid, and return it if it is.
I am getting the input via getline, but it seems that you have to press enter twice to make the input work.
Here's a sample of my code:
string getDescription(const string& thePrompt)
{
string newDescription="";
while (true)
{
cout << "\n"<< thePrompt+": " << endl;
if (getline(cin,newDescription,'\n') && cin.get() == '\n' && (newDescription!=""))
{
//valid input of new name of the record and new description contains a valid value
return newDescription;//return newDescription
}
else
{
//invalid input for some reason
//clear any cin error flags and display error message
cin.clear();
cin.sync(); //clear any remaining characters
cerr << "\nAn error occurred as an invalid value was entered.\n";
cout << "Please try again.\n";
}
}
}
What is happening, and how can I get getline to work with only one enter? Thanks!