c++c++17getline

having issue with cin.getline() when working with char data type


If I enter 12345 to arr2, why will the program skip the cin.getline(arr3,6,'#') and just finish?

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text;
    char arr2[10];
    char arr3[6];
    cout << "enter value" <<endl;
    getline(cin,text);
    cin.getline(arr2,5,'#');
    cin.getline(arr3,6,'#');
    cout << "results : " << endl;
    cout << " arr1 is : " << text << endl;
    cout <<" arr2 is : " << arr2 << endl;
    cout <<" arr3 is : " << arr3 ;
    return 0 ;
}

example of execution :

enter value
mo
12345
results :
 arr1 is : mo
 arr2 is : 1234
 arr3 is :
Process finished with exit code 0`


Solution

  • If I enter 12345 to arr2, why will the program skip the cin.getline(arr3,6,'#') and just finish?

    The line cin.getline(arr2,5,'#'); says that arr2 is a pointer to an array of 5 chars. That size includes the '\0' terminator a proper C-style string needs.

    So it can only read 4 chars from the input, and then add the terminator. When it finds more than 4 chars before the end of line, that it an input error.

    So the stream sets its fail()-state and will not read anything more until the error condition is cleared.

    Input to arr3 is skipped, because the stream is already in an error state.