Jak przekonwertować podwójny ciąg znaków w C++?

Muszę zapisać sobowtór jako ciąg znaków. Wiem, że mogę użyć printf, jeśli chcę go wyświetlić, ale chcę go przechowywać w zmiennej łańcuchowej, aby móc ją później przechowywać na mapie (jako wartość , a nie klucz ).

Author: Bill the Lizard, 2008-12-01

17 answers

The boost (tm) way:

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

The Standard C++ way:

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

Uwaga : nie zapomnij #include <sstream>

 186
Author: Johannes Schaub - litb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-25 22:09:22
// 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);
 200
Author: Adam Rosenfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-23 15:54:46

The Standard C++11 way (if you don ' t care about the output format):

#include <string>

auto str = std::to_string(42.5); 

to_string jest nową funkcją biblioteki wprowadzoną w N1803 (r0), N1982 (r1) i N2408 (r2) "prosty dostęp numeryczny". Istnieje również funkcja stod do wykonywania operacji odwrotnej.

Jeśli chcesz mieć inny format wyjściowy niż "%f", Użyj metod snprintf lub ostringstream, Jak pokazano w innych odpowiedziach.

 129
Author: kennytm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-12 15:05:36

Możesz użyć std:: to_string W C++11

double d = 3.0;
std::string str = std::to_string(d);
 26
Author: Yochai Timmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-27 12:35:09

Jeśli używasz C++, unikaj sprintf. Jest to un-c++y i ma kilka problemów. Stringstreams to metoda z wyboru, najlepiej zamknięta jak w Boost.Leksykalcast , który można zrobić dość łatwo:

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

Użycie:

string s = to_string(42.5);
 24
Author: Konrad Rudolph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-01 20:41:01

sprintf jest w porządku, ale w C++ lepszym, bezpieczniejszym, a także nieco wolniejszym sposobem wykonania konwersji jest stringstream:

#include <sstream>
#include <string>

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

Możesz również użyć Boost.Leksykalcast :

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

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

W obu przypadkach str powinno być "453.23" później. LexicalCast ma pewne zalety, ponieważ zapewnia całkowitą transformację. Używa stringstream s wewnętrznie.

 11
Author: coppro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-01 20:41:52

Spojrzałbym na C++ String Toolkit Libary . Właśnie zamieściłem podobną odpowiedź gdzie indziej. Znalazłem go bardzo szybko i niezawodnie.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );
 10
Author: DannyK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-27 22:38:04

Herb Sutter ma doskonały artykuł na temat formatowania łańcuchów. Polecam lekturę. Linkowałem to już wcześniej Na SO.

 7
Author: Fred Larson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:59

Problem z lexical_cast polega na niemożności zdefiniowania precyzji. Zwykle, jeśli konwertujesz podwójny ciąg znaków, dzieje się tak dlatego, że chcesz go wydrukować. Jeśli precyzja jest zbyt duża lub zbyt mała, wpłynie to na wydajność.

 6
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-22 15:29:59

Możesz również użyć stringstream .

 4
Author: Firas Assaad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-01 20:37:46

Heh, właśnie to napisałem (niezwiązane z tym pytaniem):

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

/* rest of the code */
 4
Author: Vinko Vrsalovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-01 20:41:21

Możesz przeczytać mój wcześniejszy post na SO. (Wersja Makro z tymczasowym obiektem ostringstream.)

Dla przypomnienia: w moim kodzie preferuję snprintf (). Z tablicą znaków na stosie lokalnym nie jest to aż tak nieefektywne. (Cóż, może gdybyś przekroczył rozmiar tablicy i zrobił to dwukrotnie...)

(zawinąłem go również poprzez vsnprintf (). Ale to mnie trochę kosztuje. Yelp jeśli chcesz Kod...)

 2
Author: Mr.Ree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:59

Spójrz na sprintf() i rodzinę.

 2
Author: Darron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-06 13:00:57

Normalnie do tych operacji trzeba użyć funkcji ecvt, fcvt lub 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   

Jako Funkcja:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}
 2
Author: Ingo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-21 15:19:36

Możesz spróbować bardziej zwartego stylu:

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(); 
 0
Author: Alexis Sánchez Tello,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-16 06:03:07

Użyj to_string().
przykład:

#include <iostream>   
#include <string>  

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

  return 0;
}

Uruchom to sam: http://ideone.com/7ejfaU
Są one również dostępne:

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);
 0
Author: Rika,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-11 16:55:15

Możesz przekonwertować dowolną rzecz na cokolwiek używając tej funkcji:

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

Użycie:

std::string str = to(2.5);
double d = to<double>("2.5");
 0
Author: Sam Mokari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-05 06:11:29