Reputation: 16445
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?
Upvotes: 3
Views: 762
Reputation: 10857
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.
Upvotes: 4
Reputation: 67417
You can thank your favorite deity that this fail-safe is in, most functions aren't that kind.
In C, strings are null-terminated, which means they take an extra character than the actual data to mark where the string actually ends.
Since you're using C++ anyway, you should avoid bare-bones char arrays. Some reasons:
string
than a plain old array. string
s have strong copy semantics that cover pretty much anything you can think of.Upvotes: 3