2014-01-28 2 views
-1

나는 두 개의 double과 한 개의 문자로 문자열을 만들려고합니다. 여기에있는 코드가 잘못되었다는 것을 알고 있지만, 내가하고 싶은 것에 대한 아이디어를 제공한다고 생각합니다.여러 개의 double과 char에서 문자열 만들기 C++

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

나는 이것을 수행하는 방법을 연구했다. 나는 sprintf와 sprintcat에 익숙하지 않지만 이것을 수행하는 가장 좋은 방법은 무엇입니까? 모든 의견을 주셔서 대단히 감사합니다!

+0

당신이 C의 ++를 사용하고 있기 때문에 , 왜 [표준 : : 문자열]을 사용하지 (http://www.cplusplus.com/reference/string/string/)? –

+4

http://stackoverflow.com/questions/4983092/c-equivalent-of-sprintf#4983095 – SGM1

+0

C 라이브러리를 사용하려면 합리적인 버퍼'char [50];를 만들고 나서'sprintf (buff, "% f % c % f", operand1, math, operand2);'나는이 것을 권장하지 않는다. – SGM1

답변

0

크기로 사용해보십시오.

std :: ostringstream 등을 사용할 수 있지만 게으름 때문에이 예제에서는 std :: stringstream을 대신 사용합니다.

#include <iostream> 
#include <sstream> 

// ... 

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

std::stringstream stream; 
stream << operand1 << " - " << operand2; 
A.push(stream.str()); 
1
double operand2 = A.pop(); 
double operand1 = A.pop(); 
char math = '-'; 
std::ostringstream oss; 
oss << operand1 << ' ' << math << ' ' << operand2; 
std::string result = oss.str(); 
...