首页 > 解决方案 > 我在 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() 函数给出了这个错误。如果您能解释这背后的原因,我将不胜感激。

标签: c++variablescastingc++17

解决方案


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

要获得 的长度std::string,您应该使用size()orlength()成员函数。

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

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

cout<<strlen(threshold.c_str())<<endl;

推荐阅读