Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 浮点到字符数组到std::string_C++_String_Std - Fatal编程技术网

C++ 浮点到字符数组到std::string

C++ 浮点到字符数组到std::string,c++,string,std,C++,String,Std,我对这段代码有点问题: string StringServices::ToStringf(float value) { char buffer[10]; sprintf (buffer, "%f", value); return (string) buffer; // signal SIGABRT } 它以前一直在工作,并继续为其他调用工作,但我目前在返回时得到一个SIGABRT,当传递函数时-211.0 缓冲区加载得很好,我真的不知道为什么这不起作用。有谁比我

我对这段代码有点问题:

string StringServices::ToStringf(float value)
{
    char buffer[10]; 

    sprintf (buffer, "%f", value);

    return  (string) buffer; // signal SIGABRT
}
它以前一直在工作,并继续为其他调用工作,但我目前在返回时得到一个SIGABRT,当传递函数时-211.0


缓冲区加载得很好,我真的不知道为什么这不起作用。有谁比我更了解std::string和c string吗?

你可能因为没有使用snprintf而溢出了缓冲区。你有这个标记C++,所以这样做:< /P> std::string buffer=boost::词法值

或者不使用boost,请使用字符串流:

std::ostringstream os;
os << value;
// os.str() has the string representation now.

您可能溢出了缓冲区,因为您没有使用snprintf。你有这个标记C++,所以这样做:< /P> std::string buffer=boost::词法值

或者不使用boost,请使用字符串流:

std::ostringstream os;
os << value;
// os.str() has the string representation now.

C及其字符串函数的主要问题是您必须手动完成太多的工作。在用C编写时,您还必须做出太多的决定。其中一个小问题是缓冲区溢出。考虑这个代码:

char buf[5]; // 5 chars, ok
sprintf(buf, "qwert"); // 5 letters, ok
这段代码会有问题,因为当谈到字符串时,5个字符表示4个字母+“\0”。因此,您可以尝试:

printf("'%s'\n", buf); // you'll probably get 'qwertIOUYOIY*&T^*&TYDGKUYTU&*#*#T^&#$T67...'
您对代码所做的只是一个微不足道的缓冲区溢出:-


sprintf无法检查buf的大小,因此buf之后的一段内存可能会损坏。

C及其字符串函数的主要问题是您必须手动执行太多的工作。在用C编写时,您还必须做出太多的决定。其中一个小问题是缓冲区溢出。考虑这个代码:

char buf[5]; // 5 chars, ok
sprintf(buf, "qwert"); // 5 letters, ok
这段代码会有问题,因为当谈到字符串时,5个字符表示4个字母+“\0”。因此,您可以尝试:

printf("'%s'\n", buf); // you'll probably get 'qwertIOUYOIY*&T^*&TYDGKUYTU&*#*#T^&#$T67...'
您对代码所做的只是一个微不足道的缓冲区溢出:-


sprintf无法检查buf的大小,因此buf之后的一段内存可能会损坏。

试试char buffer[100];你能给出一个为什么的答案吗?@loki2302:不是为了指出显而易见的原因,而是缓冲区太小,导致堆栈缓冲区溢出;内存损坏会导致未定义的行为一种可能是-211.0实际上可能是-211.00000000000001。A%f将-211.0格式化为-211.000000。超过10个字符。实际上,您不应该使用sprintf。如果出于某种原因您不能使用iostream,至少使用snprintf.try char buffer[100];你能给出一个为什么的答案吗?@loki2302:不是为了指出显而易见的原因,而是缓冲区太小,导致堆栈缓冲区溢出;内存损坏会导致未定义的行为一种可能是-211.0实际上可能是-211.00000000000001。A%f将-211.0格式化为-211.000000。超过10个字符。实际上,您不应该使用sprintf。如果出于某种原因您不能使用iostream,至少使用snprintf。在此处插入snprintf的插件。在此处插入snprintf的插件。