I got stuck for two hours trying to understand what is happening in this simple C++ test program, but still did not get it. It should just receive three strings as inputs, insert them into a stack and finally print all elements of this same stack.
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int main(){
stack<char*> stk;
int stringLength;
for (int i=0; i<3; i++){
char new_element[200];
scanf("%s", new_element);
stringLength = strlen(new_element);
stk.push(new_element);
}
cout << "Stack content: ";
while(!stk.empty()){
cout << stk.top() << " ";
stk.pop();
}
cout << endl;
}
The strange thing is that the final output is the same element (the last one added) printed 3 times, which makes no sense to me.
For example, if the inputs are:
John
Mary
Rick
then the current output is
Rick
Rick
Rick
Can anyone help me understanding and fixing this?