Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string one character shorter than defined length?

Tags:

c++

cstring

Very new to c++ and I have the following code:

char input[3];

cout << "Enter input: ";
cin.getline(input,sizeof(input));
cout << input;

And entering something like abc will only output ab, cutting it one character short. The defined length is 3 characters so why is it only capturing 2 characters?

like image 275
m0meni Avatar asked Dec 12 '25 13:12

m0meni


1 Answers

Remember that c-strings are null terminated. To store 3 characters you need to allocate space for 4 because of the null terminator.

Also as the @MikeSeymour mentioned in the comments in c++ its best to avoid the issue completely and use std::string.

like image 173
drescherjm Avatar answered Dec 14 '25 10:12

drescherjm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!