小编Jul*_*deu的帖子

不了解 C++ stack<char*> 行为

我被困了两个小时试图了解这个简单的 C++ 测试程序中发生了什么,但仍然没有明白。它应该只接收三个字符串作为输入,将它们插入一个堆栈,最后打印该堆栈的所有元素。

#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;

}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,最终输出的是同一个元素(最后添加的)打印了 3 次,这对我来说毫无意义。

例如,如果输入是:

John
Mary
Rick
Run Code Online (Sandbox Code Playgroud)

那么当前的输出是

Rick
Rick
Rick
Run Code Online (Sandbox Code Playgroud)

谁能帮我理解和解决这个问题?

c++ std stdstack

1
推荐指数
1
解决办法
60
查看次数

标签 统计

c++ ×1

std ×1

stdstack ×1