문제

두 배를 문자열로 저장해야합니다. 나는 내가 사용할 수 있다는 것을 안다 printf 표시하고 싶지만 나중에지도에 저장할 수 있도록 문자열 변수에 저장하고 싶습니다 ( , 열쇠).

도움이 되었습니까?

해결책

그만큼 부스트 (TM) 방법:

std::string str = boost::lexical_cast<std::string>(dbl);

그만큼 표준 C ++ 방법:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

메모: 잊지 마세요 #include <sstream>

다른 팁

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

그만큼 표준 C ++ 11 방법 (출력 형식에 신경 쓰지 않는 경우) :

#include <string>

auto str = std::to_string(42.5); 

to_string 소개 된 새로운 라이브러리 기능입니다 N1803 (R0), N1982 (R1) 및 N2408 (R2) "간단한 숫자 액세스". 또한 있습니다 stod 역전을 수행하는 기능.

다른 출력 형식을 갖고 싶다면 "%f", 사용 snprintf 또는 ostringstream 다른 답변에 설명 된 방법.

C ++를 사용하는 경우 피하십시오 sprintf. UN-C ++ y이며 몇 가지 문제가 있습니다. StringStreams는 선택 방법이며, 바람직하게는 boost.lexicalcast 아주 쉽게 수행 할 수 있습니다.

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

용법:

string s = to_string(42.5);

당신이 사용할 수있는 std :: to_string C ++ 11

double d = 3.0;
std::string str = std::to_string(d);

sprintf 괜찮지 만 C ++에서는 더 좋고 안전하며 약간 느리게 변환 방법이 stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

당신은 또한 사용할 수 있습니다 boost.lexicalcast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

두 경우 모두 str 해야한다 "453.23" 기후. 어휘 캐스트는 변환이 완료되도록한다는 점에서 몇 가지 장점이 있습니다. 사용합니다 stringstream내부적으로.

나는 볼 것이다 C ++ 문자열 툴킷 Libary. 방금 다른 곳에서 비슷한 답변을 게시했습니다. 나는 그것을 매우 빠르고 신뢰할 수 있음을 알았습니다.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );

Herb Sutter는 훌륭합니다 문자열 형식에 관한 기사. 나는 그것을 읽는 것이 좋습니다. 나는 전에 연결했습니다 그렇게.

lexical_cast의 문제는 정밀도를 정의 할 수 없다는 것입니다. 일반적으로 두 배를 문자열로 변환하는 경우 인쇄하려고하기 때문입니다. 정밀도가 너무 많거나 너무 적 으면 출력에 영향을 미칩니다.

당신은 또한 사용할 수 있습니다 문자열.

heh, 나는 방금 이것을 썼다 (이 질문과 관련이 없음).

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

SO에 대한 이전 게시물을 읽고 싶을 수도 있습니다. (임시 타조 스트림 객체가있는 매크로 버전.)

기록 : 내 코드에서는 snprintf ()를 선호합니다. 로컬 스택에 숯불 배열이 있으면 비효율적이지 않습니다. (어쩌면 어쩌면 배열 크기를 초과하고 두 번 반복했다면 ...)

(또한 vsnprintf ()를 통해 마무리했습니다.

보세요 sprintf() 그리고 가족.

이 작업의 경우 ECVT, FCVT 또는 GCVT 기능을 사용해야합니다.

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

함수로 :

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

보다 컴팩트 한 스타일을 시도 할 수 있습니다.

std::string number_in_string;

double number_in_double;

std::ostringstream output;

number_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<

std::endl)))->str(); 

사용 to_string().
예시 :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

직접 실행하십시오 : http://ideone.com/7ejfau
이들도 사용할 수 있습니다.

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

이 기능을 사용하여 모든 것을 무엇이든 변환 할 수 있습니다.

template<class T = std::string, class U>
T to(U a) {
    std::stringstream ss;
    T ret;
    ss << a;
    ss >> ret;
    return ret;
};

용법 :

std::string str = to(2.5);
double d = to<double>("2.5");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top