A C-style string is an array of char
s, the end of which is marked by a NUL
terminator (i.e. a char
having all its bits set to 0
).
So, the string "Hi"
looks like this in memory:
+-----+-----+-----+
| H | i | NUL |
+-----+-----+-----+
As you can note, a string of 2 characters ("Hi"
) actually requires 3 (i.e. 2+1) characters, including the NUL
terminator.
This is why a C-style string of 40 characters requires an array of 41 (i.e. 40+1) characters, because it must include room for the NUL
terminator.
As a side note, I'd suggest using a robust and convenient string class in C++ (e.g. std::string
), instead of raw C-style arrays of characters with a NUL
terminator.
If you use a string class, you'll make your code simpler, and you'll help yourself avoiding several potential security problems (e.g. buffer overruns) that are more likely to happen with raw C-style strings.
This would work just fine for string input in C++:
#include <iostream> // For std::cin/std::cout
#include <string> // For std::string
....
std::string name;
std::cin >> name; // Input
std::cout << name << std::endl; // Output