views:

534

answers:

3

I'm trying to implement prefix to infix in c++, that's what i've got so far. The input should be for example something like this:

/7+23

And the ouput:

7/(2+3) or (7/(2+3))

But instead I get:

(/)

That's the code I wrote so far:

void pre_to_in(stack<char> eq) {
    if(nowe.empty() != true) {
     char test; 
     test = eq.top();
     eq.pop();
     if(test == '+' || test == '-' || test == '/' || test == '*') {
      cout << "(";
      pre_to_in(eq);
      cout << test;
      pre_to_in(eq);
      cout << ")";
     } else {
      cout << test;
     }
    } 
} 


// somewhere in main()
char arr[30];
stack<char> stosik;
int i = 0;
cout << "write formula in prefix notation\n";
cin >> arr;

while(i < strlen(arr)) {
    stosik.push(arr[i]);
    i++;  
} 
pre_to_in(stc);
A: 
cin >> arr;

only reads one "word" of input, not a whole line. Here it's only getting the first slash character.

Jason Orendorff
+1  A: 
  1. This is a stack. First in, last out. You need reverse input string "32+7/".

  2. You use many stacks. In every enter to pre_to_in() stack is copied. Use reference or pointer, ex: void pre_to_in(stack<char> &eq);

Thats all.

P.S. Unify names (s/nowe/eq/g && s/stc/stosik/g)

rysson
Ad.1. See http://pl.wikipedia.org/wiki/Odwrotna_notacja_polskaAd.2. See http://pl.wikibooks.org/wiki/C%2B%2B/ReferencjeBoth sites in polish.
rysson
A: 

not sure if you are looking for such solution, anyway for the input you've mentioned it gives the output from you post

it reads tokens from std input

I've built it now under Visual Studio 2005 - to terminate input press Enter, Ctrl+Z, Enter

but on other compilers termination may work in another way

#include <algorithm>
#include <deque>
#include <iostream>
#include <string>

typedef std::deque< std::string > tokens_t;

void pre_to_in( tokens_t* eq ) 
{
    if ( !eq->empty() ) {
        const std::string token = eq->front();
        eq->pop_front();
        if ( ( token == "+" ) || ( token == "-" ) || ( token == "/" ) || ( token == "*" ) ) {
         std::cout << "(";
         pre_to_in( eq );
         std::cout << token;
         pre_to_in( eq );
         std::cout << ")";
        } else {
            std::cout << token;
        }
    }   
} 


int main()
{
    std::cout << "write formula in prefix notation" << std::endl;

    tokens_t tokens;
    std::copy(
        std::istream_iterator< std::string >( std::cin ),
        std::istream_iterator< std::string >(),
        std::back_inserter( tokens ) );

    pre_to_in( &tokens );
}
Dominic.wig