stack in C++



  • std::stack<int> st;
    
    	int nr;
    	int out;
    	char c;
    
    	std::cin >> nr;
    	st.push (nr);
    	std::cin >> nr;
    	st.push (nr);
    
    	std::cin >> c;
    
    	switch (c)
    	{
    	case '+':
    		out = st.top ();
    		st.pop ();
    		out += st.top ();
    		std::cout << out;
    		break;
    	case '-':
    		out = st.top ();
    		st.pop ();
    		out -= st.top ();
    		std::cout << out;
    		break;
    	case '/':
    		out = st.top ();
    		st.pop ();
    		out /= st.top ();
    		std::cout << out;
    		break;
    	case '*':
    		out = st.top ();
    		st.pop ();
    		out *= st.top ();
    		std::cout << out;
    		break;
    	default:
    		std::cout << "Falsche Eingabe.";	
    	}
    

    Wo ist das Problem? Oder musst du den Stack implementieren?!



  • Afaik funktioniert ein Stack-Rechner nach folgendem Prinzip: Wenn eine Operation ausgeführt werden soll, werden die entsprechenden Operanden vom Stack geholt und das Ergebnis wieder reingepusht.
    Also etwa so:

    stack<int> stapel;
    
    while irgendwas eingegeben wird:
        eingabe = lese_benutzereingabe()
        if eingabe ist eine zahl:
            stapel.push( eingabe als zahl )
        else
            if eingabe ist '+':
                stapel.push( stapel.get_and_pop() + stapel.get_and_pop() )
            else if ( eingabe ist '*':
                stapel.push( stapel.get_and_pop() * stapel.get_and_pop() )
            usw..
    

    e1: Oh Mist, 3 Minuten zu spät..
    e2: Dafür wird bei meinem Stack-Rechner das Ergebnis wieder zurückgepusht :p Aso, und das Ergebnis ist dann am Schluss immer das oberste Stack-Element.



  • drakon schrieb:

    Ganz rudimentär das, was ich bis jetzt verstehe, was du willst:

    und wo ist der stack? die antworten im cpp forum sind mal wieder absolute grütze.
    @OP: fang erstmal damit an:

    int stack[256];
    int stackptr = 0;
    
    #define push(x) stack[stackptr++]=(x)
    #define pop() stack[--stackptr]
    

    ist zwar auch nicht das gelbe vom ei (keine bereichsüberprüfung und so), aber wenigstens das grundgerüst eines stacks ist da.
    🙂



  • stack-freak schrieb:

    @OP: fang erstmal damit an:

    int stack[256];
    int stackptr = 0;
    
    #define push(x) stack[stackptr++]=(x)
    #define pop() stack[--stackptr]
    

    Im C-Forum wäre das evtl ok, hier gibt's aber zum Glück std::stack..



  • Badestrand schrieb:

    Im C-Forum wäre das evtl ok, hier gibt's aber zum Glück std::stack..

    du glaubst doch wohl nicht im ernst, dass jemand der fragt:

    kann mir schnell mal jemand erklären, man mit einem Stack richtig "umgeht"? Ich muss bis morgen einen Stack-Rechner für die Uni programmieren, hab leider noch nicht so wirklich einen Plan davon...

    mit std::cpp_frickeltemplate in kürzester zeit umgehen kann?
    🙂



  • mit std::cpp_frickeltemplate in kürzester zeit umgehen kann?

    $

    std::stack ist 1000 mal einfacher, als das, was du da oben gemacht hast und netterweise ist es auch noch sicherer..



  • was haltet ihr von containerklassen?



  • drakon schrieb:

    std::stack<int> st;
    
    	int nr;
    	int out;
    	char c;
    
    snip snap
    		std::cout << "Falsche Eingabe.";	
    	}
    

    Wo ist das Problem? Oder musst du den Stack implementieren?!

    HEy super das war das was ich gesucht habe, danke. Eine Frage jetzt noch: bei der eingabe 5,6, - kommt als ergebnis 1 raus... wo ist das vorzeichen?

    danke & lg



  • Bist du sicher, dass du nicht 5 von 6 subtrahierst? Überprüf das doch mal, indem du die Operanden in umgekehrter Reihenfolge eingibst. Wie sieht denn dein Code im Moment aus?
    Du hast ja kaum aus Versehen eine Funktion für den Betrag eingebaut, oder? 😉



  • Nexus schrieb:

    Bist du sicher, dass du nicht 5 von 6 subtrahierst? Überprüf das doch mal, indem du die Operanden in umgekehrter Reihenfolge eingibst. Wie sieht denn dein Code im Moment aus?
    Du hast ja kaum aus Versehen eine Funktion für den Betrag eingebaut, oder? 😉

    Mein Code steht doch da. 😉

    Und er hat das schon richtig eingegeben. 😉
    Nur wird hald von oben nach nach unten gerechnet. Müsstest das einfach noch umschreiben. Wie gesagt, ich habe das nicht gross getestet, war gestern mit Film schauen beschäftig. 😉
    Vieles ist ja eh noch unelegant, aber sollte ja kein Problem sein das zu ändern..

    Badestrand schrieb:

    e2: Dafür wird bei meinem Stack-Rechner das Ergebnis wieder zurückgepusht :p Aso, und das Ergebnis ist dann am Schluss immer das oberste Stack-Element.

    DAS ist ja wohl kein Problem auch noch zu implementieren. 😉
    Wollte ihm nur schnell helfen. Den Rest kann man ja noch in 5 Minuten dran rumbasteln.



  • Hey, people!

    It very fun that you do not know what is "Stack-Rechner" 🙂

    Old Soviet microcalculators were stack-based (I'm from Russia). That means that if you want to calculate the expression (2+3)*(4+5) then you should enter in calculator the following:

    [user enters]                  [action of calculator]              [stack state]
          2                           Push 2 to stack                        2
          3                           Push 3 to stack                       2 3
          +        Pop 3, than 2 from stack, add them, push result back      5
          4                           Push 4 to stack                       5 4
          5                           Push 5 to stack                      5 4 5
          +        Pop 5, than 4 from stack, add them, push result back     5 9
          *        Pop 9, than 5 from stack, multiply them, push result      45
    

    The top of the stack is always displayed on the screen, so you got the answer 45.
    The "Stack-Rechner" does not need in brakets (). The modern calculators translate the commands you enter on-the-fly to stack commands.



  • Nexus schrieb:

    Bist du sicher, dass du nicht 5 von 6 subtrahierst? Überprüf das doch mal, indem du die Operanden in umgekehrter Reihenfolge eingibst. Wie sieht denn dein Code im Moment aus?
    Du hast ja kaum aus Versehen eine Funktion für den Betrag eingebaut, oder? 😉

    stimmt, jetzt ist alles klar... 😉



  • SAn schrieb:

    Hey, people!
    ...

    Hi.
    Ah nice to know. I googled it, but i couldn't find anything good about a "stack-rechner".
    And I think the OP also didn't know it clear enough to explain us the situation.

    But it's not a problem to change the calculator to this functionability.



  • Here is the solution I wrote in 20 minutes (without any error checking and so on):

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <stack>
    
    using namespace std;
    
    typedef stack<double> TStack;
    
    inline double Pop(TStack& Stack)
    {
    	double result(Stack.top());
    	Stack.pop();
    	return result;
    }
    
    inline double StringToDouble(string const &String)
    {
    	istringstream Stream(String);
    	double result;
    	Stream>>result;
    	return result;
    }
    
    int main(int argc, char **argv)
    {
    	TStack Stack;
    	string Input;
    
    	while(true)
    	{
    		cin>>Input; if(Input[0]=='.') break;
    
    		switch(Input[0])
    		{
    			case '+': Stack.push(Pop(Stack)+Pop(Stack)    ); break;
    			case '-': Stack.push(-Pop(Stack)+Pop(Stack)   ); break;
    			case '/': Stack.push(1.0/Pop(Stack)*Pop(Stack)); break;
    			case '*': Stack.push(Pop(Stack)*Pop(Stack)    ); break;
    			default: Stack.push(StringToDouble(Input));
    		}
    
    		cout<<"Result: "<<Stack.top()<<endl;
    	};
    
    	cout<<"Done"<<endl;
    
    	return EXIT_SUCCESS;
    }
    

    Here is the result:

    2
    Result: 2
    3
    Result: 3
    +
    Result: 5
    4
    Result: 4
    5
    Result: 5
    +
    Result: 9
    *
    Result: 45
    .
    Done
    

    You can also enter input in one line using spaces:

    2 3 + 4 5 + * .
    Result: 2
    Result: 3
    Result: 5
    Result: 4
    Result: 5
    Result: 9
    Result: 45
    Done
    


  • SAn schrieb:

    2 3 + 4 5 + *

    Hi Brother !
    Thats RPN (Reverse Polish Notation by Jan Lukasiewicz) isnt it ?
    I wrote such a calculator/parser last year^^ 🕶



  • Big Brother schrieb:

    Hi Brother !
    Thats RPN (Reverse Polish Notation by Jan Lukasiewicz) isnt it ?
    I wrote such a calculator/parser last year^^ 🕶

    Yes, that is RPN. And the "stack computer" is the simple parser which can process RPN.


Anmelden zum Antworten