Program is skipping getline () / C++

64 views Asked by At

Whenever i try to run this code :

string title;
        int Choice;
        cout<<"1. Insert new term ";
        cin>>Choice;
        if (Choice==1)
        {
            getline(cin,title);
        }

the program only read the Choice and end the whole process :/ , help please :D

2

There are 2 answers

1
StoryTeller - Unslander Monica On BEST ANSWER

cin>>Choice; leaves the trailing newline character in the input buffer. And getline(cin,title); therfore reads an empty line.

In general, it's better not to mix formatted input with getline from the same stream.

A quick and easy fix is to remove the trailing newline character from the stream using std::basic_istream::ignore, like so:

cin.ignore(2, '\n');
0
Vlad from Moscow On

After this statement

    cin>>Choice;

the input buffer will contain the new line character left by pressing the Enter key.

So the next statement with getline

    if (Choice==1)
    {
        getline(cin,title);

reads an empty string until the new line character is encountered.

Insert before this statement the following call

    #include <limits>

    //...


    {
        getline(cin,title);
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

to clear the buffer.