cin doesn't know the size of 'array', so any input that is to long for the array to hold gets written to whatever happens to be after 'array'
In your example case I'm guessing that the stack is 4-byte aligned and your input is only 4 bytes long so nothing bad happens. Try inputting a really long string and the application will probably crash from stack corruption.
Consider the following code:
Code:
#include <iostream>
#pragma pack(push, 1) // change data alignment
struct test
{
test() : foo(12345) {}
char str[2];
int foo;
};
#pragma pack(pop) // restore old alignment
int main(void)
{
test t;
std::cout << "t.foo is " << t.foo << std::endl;
std::cout << "Enter text for t.str: ";
std::cin >> t.str;
std::cout << "t.foo is " << t.foo << std::endl;
return 0;
}
I'm using visual c++ pragmas to make sure the struct is byte-aligned. There are ways to do the same in gcc but I can't remember how exactly.
But anyways, the output for me was
Code:
t.foo is 12345
Enter text for t.str: abc
t.foo is 99
As you can see foo gets overwritten by 99 (ASCII code for 'c') because the input is to long for the array.
So do what laserlight suggested and limit the length of the input, or use an std::string.
Edit:
By the way, when using cin for input; Is there anything in the standard that specifies how long input strings it can handle or is that implementation specific?