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); 
3
  • 1
    Is this homework? If so, tag it as such. Commented Dec 9, 2009 at 22:39
  • 3
    Thank you for trying the problem first, then showing us all the information you have. Thank you. Commented Dec 9, 2009 at 22:39
  • 2
    Do you mean to copy by value, or did you forget a &, ie: pre_to_in(stack<char>& eq) ? Commented Dec 9, 2009 at 22:41

3 Answers 3

1
cin >> arr; 

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

Sign up to request clarification or add additional context in comments.

1 Comment

Blame on me, i added extra spaces to clarify input & output. Question fixed. That's not a solution, unfortunately.
1
  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)

1 Comment

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.