[英]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 转换为字符串。 阈值包含像 3.00000 这样的值,而 strlen() function 给出了这个错误。 如果您能解释这背后的原因,我将不胜感激。
strlen()
用于计算 C 风格字符串的长度。
要获得std::string
的长度,您应该使用size()
或length()
成员 function。
cout<<threshold.length()<<endl;
如果您想坚持使用strlen()
,可以使用c_str()
成员 function 从std::string
获取 C 样式字符串。
cout<<strlen(threshold.c_str())<<endl;
您应该改用字符串 stream 。
#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(float or double) 的情况下,小数点后的 8 位将插入结果字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.