c++ - 如何将从文本文件中读取的元素推送和弹出到 C++ 中的数组并以相反的顺序输出堆栈?

标签 c++ arrays stack

您好,我是 C++ 的新手,我无法理解如何将文本文件中的元素推送和弹出到数组并以相反的顺序显示这些元素,例如,如果我有一个名为 hero.txt 的文本文件元素 Goku Luffy Naruto 我希望输出是 Naruto Luffy Goku 这是我目前所拥有的

    string hero[100]; // array to store elements
    int count=0;

    int main()
    {   
        fstream myfile;
        string nameOffile;
        string text;
        string mytext;
        cout << "Enter name of file" << endl;
        cin >> nameOffile
        myfile.open(nameOffile.c_str());
            if (!myfile) 
            {
                cerr << "error abort" << endl;
              exit(1);   
            }
           while (myfile >> text ) 
            {  

               Push(mytext); //Note I know this is wrong I just don't know how to write it in a manner that will push the first element of the textfile to the top


            }

        myfile.close();

        while(hero[count]=="")
        {
//Again I know these two lines are incorrect just don't know how to implement in correct manner


            cout <<hero[0] << " " <<endl; 
            Pop(mytext);


        }

    }

// Function for push
void Push(string mytext)
{
    count = count + 1;
    hero[count] = mytext;

}

void Pop(string mytext)
{
    if(count=0)
    {
        mytext = " ";

    }
    else 
    {
        mytext = hero[count];
        count = count - 1;
    }

}

最佳答案

通常情况下,堆栈会以index = -1 开头,表示堆栈为空。所以你需要更换

int count = 0 

int count = -1

完成所有推送后,您的堆栈将如下所示:

hero[0] = "Goku"
hero[1] = "Luffy"
hero[2] = "Naruto"

现在,要以相反的顺序打印出来,您可以从最后一个索引循环到第一个。压入所有英雄字符串后,count 现在等于 2。最后的英雄将位于 index = 0。所以你可以将循环重写为

while(count >= 0)
{
    cout << hero[count] << " " <<endl; 
    Pop();
}

您的 Pop 函数也不正确。在 if 语句中,您会将 count 的值替换为 0。在 Pop 中您需要做的只是减少 count 的值。 所以你可以把它重写为

void Pop()
{
    count = count - 1;
}

关于c++ - 如何将从文本文件中读取的元素推送和弹出到 C++ 中的数组并以相反的顺序输出堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45413095/

相关文章:

c++ - 如何在window系统中读出磁盘驱动序号?

javascript - 如何在 Angular 或 Javascript 中获取多个对象中的数组结果?

c++ - 在源文件中定义数组并在其他源文件中使用它

C 字符串递归堆栈复制还是...?

java - 当之前的测试在我的双链表中正常工作时,代码在节点中存储错误的数据,并给我一个 OutOfMemoryError

java - 为什么我们可以实例化堆栈而不是队列?

c++ - 改变图像部分的亮度和对比度

c++ - 从 C++ 调用 Fortran;返回损坏的字符串

javascript - 如何将带有 ArrayBuffer 的 JSON 对象发送到 websocket?

c++ - 错误: 'high_resolution_clock' has not been declared