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

58 Views Asked by At

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`

2

There are 2 best solutions below

0
BoP On BEST ANSWER

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.

0
0xAR33B On

the last parameter in cin.getline() is what indicates that the input is ended i.e. the delimiter. Replace the lines with your code to fix.

cin.getline(arr1,10,'\n');
cin.getline(arr2,10,'\n');
cin.getline(arr3,6,'\n');

The syntax is cin.getline(your_array, max_characters, delimiter);

\n means line break (In case of this code, it represents ENTER press)


Don't forget to Declare arr1 as it's declaration is missing in your code...