When I execute the code below, I get the following...
ISBN: 1234
Title: Author:
I can enter an ISBN number no problem, but I don't get a chance to enter a title. It just prints the prompts 'title' and 'author' one after the other. It's as if there is a string waiting in the keyboard buffer to be input into title. I tried printing out the string 'title' but there is nothing there. Am I using getline incorrectly?
#include <iostream>
#include <string> // *** required
int main()
{
std::cout << "ISBN: ";
std::string isbn;
std::cin >> isbn; // this is formatted input
// formatted input operations leave unconsumed characters
// (typically white spaces - new line, space, tab etc.) in the input buffer
// after this, there would be a new line left in the input buffer
// extract and throw away stuff remaining in the input buffer
// (max 1000 characters, up to and including the new-line).
std::cin.ignore( 1000, '\n' ) ;
std::cout << "Title: ";
std::string title;
std::getline( std::cin, title ); // this is unformatted input
// unformatted input does not skip over leading white space characters
// if we hadn't extracted and thrown away the new line remaining in the
// input buffer, this would have typically read an empty string into title
std::cout << "Author: ";
std::string author;
std::getline( std::cin, author ); // fine: the earlier unformatted input would have
// extracted and thrown away the trailing new-line
}