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!

Well you are calling getline and get so you need to hit enter twice. What is the purpose of using cin.get() in your if statement? getline will toss it out so there would be nothing there.

Thanks very much with your comment. My purpose with cin.get() was to check if a person entered in appropriate response... ex: if you want the price, you want a single number (decimal). you would not want this: 35.56 499, right?
So if you had, this for example, then

if (cin >> var && cin.get() == '\n)
{
    //this means that the cin >> var operation worked successfully,
    //and that only one word was inputted
}

I confused it with getline, so that's my mistake on my part. Thanks!

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.