3

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?

harper
  • 13,345
  • 8
  • 56
  • 105
m0meni
  • 16,006
  • 16
  • 82
  • 141
  • 2
    ***The defined length is 3 characters so why is it only capturing 2 characters?*** You need an extra character for the null terminator. – drescherjm Feb 24 '15 at 18:19
  • Thank you! If you post this as an answer I'll accept it. – m0meni Feb 24 '15 at 18:21
  • 3
    If you're new to C++, don't use weird quirks like C-style strings yet. Use `std::string`, which just works how you'd expect, then learn how it works when you're ready to face true madness. – Mike Seymour Feb 24 '15 at 18:22

2 Answers2

4

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.

drescherjm
  • 10,365
  • 5
  • 44
  • 64
3

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.
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • Could you expand upon Unicode awareness? I'm not exactly familiar with what that means, and why having 256 characters is unacceptable. – m0meni Feb 24 '15 at 18:50
  • 1
    I take it you're American. The world unfortunately is in majority non-American, and some of those crazy non-Americans have goofy ways of writing, and those goofy characters don't fit in your cozy little 256 characters. 미안해! – Blindy Feb 24 '15 at 19:00