My question revolves around the program shown below (environment is Mac Xcode).
#include <iostream>
int main () {
char nameOne [5];
std::cin >> nameOne; // input: BillyBobThorton
std::cout << nameOne; // output: BillyBobThorton
char nameTwo [5] = "BillyBobThorton"; // compile error, initializer string too long
std::cout << nameTwo;
return 0;
}
I have a char array of length 5, so I would expect the maximum amount of characters I could store in this array to be 4 (plus the null terminating char). And this is indeed the case when I attempt to store a string to the nameTwo variable. However, when I use an array of characters as the variable to store user input, the array length is outright ignored and the array seemingly expands to accomodate the extra characters.
Why is this the case, and is there perhaps a more appropriate way to store user input to an array of characters?
Is there perhaps a more appropriate way to store user input to an array of characters?
Yes! The most appropriate way in C++ is to use
std::string. This will prevent your user overrunning the end of the buffer you’ve allocated and corrupting your stack. If you only want to display a certain number of characters, you can limit on output (or during some validation routine) usingstd::string::substr(). Here’s an example.