c++ - 我在 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() 函数给出了这个错误。如果您能解释这背后的原因,我将不胜感激。
解决方案
strlen()
用于计算 C 风格字符串的长度。
要获得 的长度std::string
,您应该使用size()
orlength()
成员函数。
cout<<threshold.length()<<endl;
如果你想坚持使用strlen()
,你可以使用c_str()
成员函数从std::string
.
cout<<strlen(threshold.c_str())<<endl;
推荐阅读
- java - Java:定义为全局变量时处理 IOException
- mysql - MySQL注入绕过点(。)和逗号(,)
- c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?
- siddhi - 我们可以使用 REST api 作为 Siddhi 事件表的数据源吗?
- c++ - CMake 标头仅依赖项
- go - 如何在 Golang 中使用 gobuffalo/packr
- python - 确定没有扩展名的文件的文件类型
- python - 根据以前的任务为 5 个 python 脚本创建管道
- binary - 为了清晰和简单,如何使用十六进制改进我的文本文件代码?
- php - 无法将变量传递给 jquery