0

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

M.Hamza Al Omari
  • 373
  • 1
  • 3
  • 8

2 Answers2

1

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');
StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399
0

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.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268