Abinash Nanda
Abinash Nanda

Reputation: 57

Why the second character is getting lost for the second variable

I have 2 variables of char type.

char desc[30];
char code[2];
cout << "Enter values : "<<"\n";
cin.getline(desc,30);
cin.getline(code,2);

cout << "\nValues Entered: "<<"\n";
cout << desc <<"\t";
cout << code <<"\n";

When the input values are provided as below, the second character for the second variable is lost. I have tried cin>>marks and cin.get(marks,2), but the behaviour is always same.

Enter values :
This is a test line
LH

Values Entered:
This is a test line     L

Process returned 0 (0x0)   execution time : 11.285 s
Press any key to continue.

In the example above even though the input is LH, in the output only 'L' is available and 'H' is lost. Can someone advise what is wrong here?

Upvotes: 3

Views: 86

Answers (1)

Blaze
Blaze

Reputation: 16876

Take a look at the documentation of getline (emphasis mine):

Maximum number of characters to write to s (including the terminating null character).

So if you want to read in two symbols, you have to put a size of 3.

cin.getline(code,3);

Change your buffer size to 3, too:

char code[3];

Upvotes: 7

Related Questions