-1

I'm trying to make a string out of a couple doubles and a character. I know my code here is wrong but I think it gives an idea of what I want to do.

operand2 = A.pop();     //double
operand1 = A.pop();     //double
math = "-";             //char
result = "%f %s %f",operand1, math, operand2;     //string
A.push(result);

I have tried researching how to do this. I am unfamiliar with sprintf and sprintcat, but is that the best method to go about doing this? Thank you so much for any input!

whla
  • 739
  • 1
  • 12
  • 26
  • Since you're using C++, why not use [std::string](http://www.cplusplus.com/reference/string/string/)? – David Schwartz Jan 28 '14 at 23:08
  • 4
    http://stackoverflow.com/questions/4983092/c-equivalent-of-sprintf#4983095 – SGM1 Jan 28 '14 at 23:09
  • If you want to use the C library, you make a reasonable buffer `char buff[50];` and then you `sprintf(buff, "%f %c %f", operand1, math, operand2);` I DO NOT RECOMMEND THIS – SGM1 Jan 28 '14 at 23:13
  • Might also be interested in `std::to_string` – Aesthete Jan 28 '14 at 23:15

2 Answers2

1
double operand2 = A.pop();
double operand1 = A.pop();
char math = '-';
std::ostringstream oss;
oss << operand1 << ' ' << math << ' ' << operand2;
std::string result = oss.str();
...
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Try this on for size.

You can be specific and use std::ostringstream, etc. But due to laziness this example makes use of std::stringstream instead.

#include <iostream>
#include <sstream>

// ...

double operand2 = A.pop();
double operand1 = A.pop();

std::stringstream stream;
stream << operand1 << " - " << operand2;
A.push(stream.str());
Son-Huy Pham
  • 1,899
  • 18
  • 19