Nothing special - I just need to grab a line and slap it into a string -

    if(found == 1)
    {
       cout << "\n\n Please enter a new location for this event: \n";
       getline(cin,newAct);
       cout << "New Account: " << newAct << endl;

    }
    else
    {
        cout << "\nEvent not found\n";
    }
    eventList[eventSlot].newActivity(newAct);
    menu(eventList);

For some reason as soon as it hits this block - it ignores it and just prints New Account - it doesn't even allow me to type in anything - it kinda crappily works (ie: it grabs like the last 3 chars of the entry) if I cin.ignore('\n') a line ahead, but I thought getline didn't need that. So frustrated and so confused -

C++ input streams have two different modes of input. When we use the >> operator, we are doing formatted input; when we don't (for instance we do a std::getline() or a std::cin.getline() ) we are doing unformatted input.

The formatted input operator >> discards leading white space, and stops reading when it encounters a white space (or invalid input). Unformatted input on the other hand, does not discard leading whitespace.

Now let us say, we want to read an int (using formatted input) and a string (using unformatted input) from stdin. We write:

int number ;
std::string text ;
std::cin >> number ;
std::getline( std::cin, text ) ;

We run the program and enter 12345<newline> on stdin. std::cin >> number ; reads 12345 into number and leaves the <newline> in the input buffer. The program continues with std::getline( std::cin, text ) ; The getline() sees that the input buffer is not empty, so it does not wait for any input to be entered. It returns immediately after reading an empty string, and extracting the <newline> in the buffer and throwing it away.

One solution to the problem is not to mix formatted and unformatted input.

Another is to make the stream discard trailing white space left by the formatted input operation. This can be done by:

int number ;
std::string text ;
std::cin >> number ;
std::cin.ignore( 1024, '\n' ) ;
std::getline( std::cin, text ) ;

std::cin.ignore( 1024, '\n' ) ; will extract and discard up to 1024 characters or until a '\n' is extracted and thrown away. The 1024 in the example is just a reasonably large enough value.

A more robust, pedantically correct, version would be:
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;

This article has been dead for over six months. Start a new discussion instead.