我在 C++ 中将浮点变量转换为字符串时遇到问题

I have an issue converting a float variable into a string in C++

我不是使用 C++ 的专家,所以我需要一些帮助。考虑以下代码:

 float thresh = 3.0;
 string threshold = to_string(thresh);
 cout<<strlen(threshold)<<endl;

终端显示此错误:

error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to 
‘const char*’ for argument ‘1’ to ‘size_t strlen(const char*)’
cout<<strlen(threshold)<<endl;

我在这里做错了什么?我只想将 3.0 转换为字符串。 threshold 包含一个类似于 3.00000 的值,strlen() 函数会给出此错误。如果您能解释一下这背后的原因,我将不胜感激。

strlen()用于计算C风格字符串的长度。

要获取std::string的长度,应该使用size() or length()成员函数。

cout<<threshold.length()<<endl;

如果你想坚持使用strlen(),你可以使用c_str()成员函数从std::string.

中获取C风格的字符串
cout<<strlen(threshold.c_str())<<endl;

您应该改用字符串流。

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    float thres = 3.0;
    ostringstream out;
    out.precision(1);
    out << fixed << thres;
    string threshold = out.str();
    cout << threshold.length() << endl;

    return 0;
}

如果是 to_string(浮点数或双精度数),小数点后的 8 位数字将插入到结果字符串中。