简体   繁体   中英

how to push and pop elements read from a textfile to an array in c++ and output the stack in revserse order?

Hi I am new to c++ and am having trouble understanding on how I would push and pop elements read from a text file to an array and displaying those elements in reverse order for example if i have a text file called hero.txt with elements Goku Luffy Naruto I would like the output to be Naruto Luffy Goku this is what I have so far

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

}

Normally, a stack will begin with index = -1 to indicate that the stack is empty. So you need to replace

int count = 0 

with

int count = -1

After you do all the pushing, your stack will look like this:

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

Now, to print it out in reverse order, you can just loop from the last index to the first. After pushing all the heroes string, count is now equal to 2. The last heroes will be at index = 0 . So you can rewrite the loop as

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

Your Pop function is also incorrect. In the if statement, you will replace the value of count to 0 . What you need to do in Pop is just to decrement the value of count . So you can rewrite it as

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

ok let's tart by improving your functions

push function works good but just change the order of it to be like this

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

pop function should be like this

you need to return a string value and you don't need to pass a parameter

string Pop()
{
    if(count == 0)
    {
        return "";
    }
    else 
    {

        count = count - 1;
        mytext = hero[count];
        return mytext;
    }

}

now you are functions are ready let's use them

you are using the push function correctly in your main

we need to change the while which displays the output

it should be like this

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;

        }

The vector class defined in the standard library acts like a stack. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM