Question About Getline

This is a discussion on Question About Getline within the C++ Programming forums, part of the General Programming Boards category; Hi, I've been programming some examples out of a book and I've noticed something about getline that's made me curious. ...

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    127

    Question About Getline

    Hi,

    I've been programming some examples out of a book and I've noticed something about getline that's made me curious. In the following simple program, you enter a make and model of a car, and then it outputs it.

    But say you change the line "cin.getline(make, 19);" to "cin.getline(make, 3);". Then, if you enter something like "ford" or anything longer than that, the program no longer asks you the second question. How come?

    Code:
    #include <iostream>
    using namespace std;
    
    char model[20];
    char make[20];
    
    int main()
    {
        cout << "Enter make: ";
        cin.getline(make, 19);
        cout << "Enter model: ";
        cin.getline(model, 19);
    
        cout << make << " " << model;
        return 0;
    }
    Thanks.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    Because there are still characters in the input buffer since the first cin.getline() call did not read everything. The characters that are left over get assigned to model.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Actually not. When the line is longer the stream goes into a failed state.

    For this reason getline with C style strings is hard to use (I've never used it in practice). Use std::string, its version of getline and you won't have these worries:

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    int main()
    {
        string make, model;
        cout << "Enter make: ";
        getline(cin, make);
        cout << "Enter model: ";
        getline(cin, model);
    
        cout << make << " " << model;
        return 0;
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 01:14 PM
  2. A question about getline
    By jriano in forum C++ Programming
    Replies: 2
    Last Post: 06-24-2003, 03:21 AM
  3. getline question
    By Swaine777 in forum C++ Programming
    Replies: 2
    Last Post: 03-30-2003, 06:17 AM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. getline question
    By Kings in forum C++ Programming
    Replies: 9
    Last Post: 01-20-2003, 01:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21