Thread: cin.getline(something,3);

  1. #1
    Registered User
    Join Date
    Jan 2008
    Location
    Malaysia
    Posts
    13

    cin.getline(something,3);

    I don't understand how this piece of function
    Code:
    cin.getline(response,3);
    , work. I thought this cin.getline function is to get user input? I tried to key in the name TOM, but it turns out that only TO appeared in the cout object. Why is that so? I then tried
    Code:
    cin.getline(response,4);
    and I key in TOM again. This time, all the words was displayed. Why does changing 3 to 4 helped? I thought 3 is the number of characters that allowed to be shown?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    That version of getline works with C style strings. In C++ you should probably work with C++ strings instead. If you used those, then you would not have to specify the number of characters, the string class would automatically grow to fit whatever the user types in.

    The problem you are having is because C style strings require space for a terminating null character. This extra character is added to the end of the array to signal the end of the string. The number you pass to getline is the size of the string, including the spot for that null character.

    So when you pass 3, then getline reads in 'T' and 'O' and then adds the terminating null character '\0' in the third spot.

    Here is an example using C++ strings:
    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
        using namespace std;
    
        string response;
        getline(cin, response);
    
        cout << "Your response was: " << response << '\n';
    }

Popular pages Recent additions subscribe to a feed