m0meni
m0meni

Reputation: 16445

C string one character shorter than defined length?

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

Answers (2)

drescherjm
drescherjm

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

Blindy
Blindy

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:

  • buffer overflows. You managed to hit this issue on your first try, take a hint!
  • Unicode awareness. We're living in 2015. Still using 256 characters is unacceptable by any standard.
  • memory safety. It's way harder to leak a proper string than a plain old array. strings have strong copy semantics that cover pretty much anything you can think of.
  • ease of use. You have the entire STL algorithm list at your disposal! Use it rather than rolling your own.

Upvotes: 3

Related Questions