This is undefined behavior (UB):
scanf(answer);
scanf
function will interpret the uninitialized content of answer
as the format string, causing UB.
It should be like this:
scanf("%1s", answer);
Note that when you declare a character array of size 2, it means that it could fit a C string of length at most 1, because you need one character for null terminator.
Note that when you enter more than two characters for the name in your C++ program, you get undefined behavior too: writing past the end of the array is UB. Fortunately, it is very rare to need to read a string into a character array in C++, because the standard C++ library supplies a dynamically resizing class std::string
, a much better choice for representing strings.