【问题标题】:how to push and pop elements read from a textfile to an array in c++ and output the stack in revserse order?如何将从文本文件读取的元素推送和弹出到C++中的数组并以相反的顺序输出堆栈?
【发布时间】:2018-01-06 20:39:52
【问题描述】:

您好,我是 C++ 新手,我无法理解如何将从文本文件读取的元素推送和弹出到数组并以相反的顺序显示这些元素,例如,如果我有一个名为 hero.txt 的文本文件元素悟空路飞火影忍者我希望输出是火影忍者路飞悟空 这就是我到目前为止所拥有的

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

}

【问题讨论】:

  • en.cppreference.com/w/cpp/container/stack。这是一个模板类,因此在将其声明为std::stack&lt;std::string&gt; mystack 后,您可以将其用作mystack.push(mystring);。顺便说一句,您有textmytext,并且您以混合方式使用它们。当然它应该只是一个。
  • 您好,谢谢,但我想避免使用模板类,因为我还是 C++ 新手
  • 遗憾的是,这是堆栈的标准实现。实际上,这并不难。声明是您必须编写的模板实例化的唯一行。对于其他每一行,它将表现得与任何其他类一样。如果实在不想用,可以趁机编写自己的StringStack类。

标签: c++ arrays stack


【解决方案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;
}

【讨论】:

    【解决方案2】:

    标准库中定义的vector 类就像一个堆栈。 例如:

    // include the library headers
    #include <vector>
    #include <string>
    #include <iostream>
    
    // use the namespace to make the code less verbose
    using namespace std;
    
    int main()
    {
        // declare the stack
        vector<string> heroStack;
    
        // insert the elements
        heroStack.push_back("Goku");
        heroStack.push_back("Luffy");
        heroStack.push_back("Naruto");
    
        // print elements in reverse order
        while(!heroStack.empty())
        {
            // get the top of the stack
            string hero = heroStack.back();
            // remove the top of the stack
            heroStack.pop_back();
    
            cout << hero << endl;
        }
    }
    

    【讨论】:

      【解决方案3】:

      好的,让我们开始改进你的功能

      push 函数很好用,只是把它的顺序改成这样

      void Push(string mytext)
      {
          hero[count] = mytext; //now you will start at index 0
          count = count + 1;
      }
      

      pop函数应该是这样的

      需要返回一个字符串值,不需要传参数

      string Pop()
      {
          if(count == 0)
          {
              return "";
          }
          else 
          {
      
              count = count - 1;
              mytext = hero[count];
              return mytext;
          }
      
      }
      

      现在你的功能已经准备好了,让我们使用它们

      您在 main 中正确使用了 push 功能

      我们需要改变显示输出的while

      应该是这样的

      while(true)
              {
                  tempText = pop(); // this function will get you the last element and then remove it
                  if ( tempText == "" ) // now we are on top of the stack
                      break;
      
                  cout <<tempText << " " <<endl;
      
              }
      

      【讨论】:

        【解决方案4】:
            #include "stdafx.h"
            #include <fstream>
            #include <stack>
            #include <string>
            #include <iostream>
        
            class ReadAndReversePrint
            {
                std::stack<std::string> st;
                std::ifstream file;
              public:
                ReadAndReversePrint(std::string path)
                {
                   file.open(path);
                   if (file.fail())
                   {
                       std::cout << "File Open Failed" << std::endl;
                       return;
                }
                std::string line;
                while (!file.eof())
                {
                    file >> line;
                    st.push(line);
                }
                file.close();
        
                std::cout << "Reverse printing : " << std::endl;
                while (!st.empty())
                {
                    std::cout << st.top().c_str() << "\t";
                    st.pop();
                }
                std::cout << std::endl;
            }
        };
        
        
        int main()
        {
            ReadAndReversePrint rrp("C:\\awesomeWorks\\input\\reverseprint.txt");
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2020-08-18
          • 2019-01-07
          • 2022-11-28
          • 1970-01-01
          • 1970-01-01
          • 2021-12-14
          • 1970-01-01
          • 2016-06-29
          • 1970-01-01
          相关资源
          最近更新 更多