Problem with getline()

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?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
    cout << "ISBN: ";
    string isbn;
    cin >> isbn;

    cout << "Title: ";
    string title;
    getline( cin, title );

    cout << "Author: ";
    string author;
    getline( cin, author );

    return 0;
}



when I input the ISBN using getline too, everything works fine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{
    cout << "ISBN: ";
    string isbn;
    getline(cin, isbn);

    cout << "Title: ";
    string title;
    getline( cin, title );

    cout << "Author: ";
    string author;
    getline( cin, author );

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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
}
Thanks, I'm getting lots of mileage out of this one already.
Topic archived. No new replies allowed.