I am reading C ++ Primer Plus (6th edition), and I came across some code example in chapter 4 in which I have a question:
Listing 4.2 strings.cpp
// strings.cpp -- storing strings in an array
The code itself is not confusing, but I ran it, and I am confused by a specific scenario.
name1 is initialized as an array of characters with a length of 15 elements. Do I think it should contain a string of 14 characters? The end of char must be reserved for the string terminator, right?
If I enter my name as HowCanIPossiblyFitThisEntireStringIn? I get the following output:
Howdy! I am C ++ owboy! What is your name?
HowCanIPossiblyFitThisEntireStringIn?
Well, HowCanIPossiblyFitThisEntireStringIn ?, your name has 37 letters and is stored
in an array of 15 bytes.
H. first
Here are the first 3 characters of my name: C ++
How is the whole name that I entered written down? If I go through the code after reading cin in name1, Visual Studio will tell me that it contains elements 0-14, the last of which is char 'y' ("HowCanIPossibly ...). I would suggest that any extra input the data was truncated and lost, but this is obviously not the case, since the next cout successfully writes the entire name to the console.
For curiosity, can someone enlighten me about what is happening here? For recording I use Visual Studio 2012 Express.
source share