cin >> n;
char a[n];
Variable-length arrays are not standard C++. Fixed-length arrays must have their sizes known at compile-time. For arrays whose sizes are not known until runtime, you must use new[]
or better std::vector
instead.
Why aren't variable-length arrays part of the C++ standard?
cin >> a;
This exhibits undefined behavior. You have allocated space for the array to hold only 3 chars, but your input has 5 chars, plus a null terminator. operator>>
has no idea how much memory you have allocated, it simply reads input until a whitespace char is encountered. So, you are reading 5 chars and a null terminator into the array, overflowing the array and writing into surrounding memory. And since the array is allocated on the stack, you may end up with a runtime error about stack corruption (if you have configured your compiler to enable that option).
To do what you are attempting, you would need to allocate +1 more char to account for the null-terminator, and then use cin.get()
instead of operator>>
so you can specify the max size of the array being written into, eg:
char *a = new char[n+1];
cin.get(a, n+1);
...
delete[] a;
Or
std::vector<char> a(n+1);
cin.get(a.data(), n+1);
...
cout << a;
This just prints from memory until a null terminator is reached. It has no concept what the allocated size of the array is, or that you are asking it to print from corrupted memory. That is why you see the full input being printed.