1

I have string

 string s1="5 2 13 * +" //as prefix expression.

I want to obtain reversed of above matrix like this.

"+ * 13 2 5"

I have tried stringstream but it make "+ * 31 2 5" and I lost my "13" and I gets "31". This not good my computation.

How can I do? For helping thanks.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
burakim
  • 472
  • 1
  • 4
  • 20
  • @juanchopanza "13" will still get reversed, right? – Fiddling Bits Nov 28 '13 at 21:37
  • 2
    @BitFiddlingCodeMonkey silly me, I keep thinking the question titles mean something. – juanchopanza Nov 28 '13 at 21:38
  • 2
    Looks like you do not want to reverse the "string". You have a two dimensional array like [["5"],["2"], ["13"], ["*"], ["+"]] and you want to reverse the outer array. Hope that answers your question too :-) – rnk Nov 28 '13 at 21:40
  • You'll probably need `strtok()` – Fiddling Bits Nov 28 '13 at 21:44
  • Note that this is probably not the answer to the question you really wanted to ask, which is how to change postfix to prefix. The correct answer is `+ 5 * 2 13`. Of course, `+` and `*` are commutative so the end result is the same, but there are operators which are not. Try, for example, `5 2 13 / -` which is certainly not the same as the prefix expression `- / 13 2 5`. – rici Nov 28 '13 at 22:14

2 Answers2

4

Assuming that what you want to reverse is in str and the delimiters between values are whitespace characters:

stringstream ss(str);
string answer, current;
answer.clear();
while (ss >> current) answer = current + " " + answer;
answer.erase(answer.size()-1, 1);     // eliminate space in the end of answer
yasen
  • 1,250
  • 7
  • 13
1

Another way

    std::string s = "5 2 13 * +";
    std::forward_list<std::string> lst;
    std::istringstream is( s );

    for ( std::string t; std::getline( is, t, ' ' ); ) lst.push_front( t );
    s.clear();

    for ( std::string t : lst ) s += t + ' ';

    std::cout << "s = " << s << std::endl;

Or without std::getline

    std::string s = "5 2 13 * +";
    std::forward_list<std::string> lst;
    std::istringstream is( s );

    while ( is >> s ) lst.push_front( s );

    s.clear();
    for ( std::string t : lst ) s += t + ' ';

    std::cout << "s = " << s << std::endl;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335