将double转换成字符串C ++? [英] Convert double to string C++?
问题描述
可能重复:
如何将双精度转换为C ++中的字符串?
我想结合一个字符串和一个double,g ++抛出这个错误:
I want to combine a string and a double and g++ is throwing this error:
main.cpp:In函数'int main()':
main.cpp:40:错误:类型为const char [2]和double的无效操作数到二进制运算符+
main.cpp: In function ‘int main()’:
main.cpp:40: error: invalid operands of types ‘const char [2]’ and ‘double’ to binary ‘operator+’
以下是代码中的错误代码:
Here is the line of code which it is throwing the error on:
storedCorrect[count] = "("+c1+","+c2+")";
storedCorrect []是一个字符串数组,并且c1和c2均为双精度。有没有办法将c1和c2转换成字符串来允许我的程序正确编译?
storedCorrect[] is a string array, and c1 and c2 are both doubles. Is there a way to convert c1 and c2 to strings to allow my program to compile correctly?
推荐答案
你不能这样做直。有很多方法可以实现:
You can't do it directly. There are a number of ways to do it:
-
使用
std :: stringstream
:
std::ostringstream s;
s << "(" << c1 << ", " << c2 << ")";
storedCorrect[count] = s.str()
storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
使用 std :: snprintf
:
char buffer[256]; // make sure this is big enough!!!
snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
storedCorrect[count] = buffer;
还有其他一些方法,使用各种双字符串转换功能,但这些是您将看到完成的主要方式。
There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.
这篇关于将double转换成字符串C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!