【问题标题】:invalid operands of types 'float' and 'const c''float' 和 'const c' 类型的无效操作数
【发布时间】:2025-12-27 13:20:23
【问题描述】:

我刚开始学习 C++,需要一些帮助。

targetDistance 是一个float 变量,我想给它添加一个字符串"a",可以吗?

我试过了:

  targetDistance = targetDistance <<"a"

它给了我这个错误:

 invalid operands of types 'float' and 'const c'

【问题讨论】:

  • 不,这是不可能的。我想知道您打算将字符串“添加”到浮点数的目的是什么?听起来像是一个误解。
  • 你想让targetDistance在你这样做之后变成一个字符串吗?
  • 确实有一些good C++ books 可以帮助学习如何使用 C++ 编程。
  • 就像在python中我会做targetDistance = targetDistance+"a"
  • @strilz:C++ 与 Python 不同。在 Python 中,对变量的赋值也会设置它的类型。在 C++ 中,类型不会改变,所以它必须匹配。 (至少粗略地 - 允许像 int 到 float 这样的次要转换)

标签: c++ string floating-point


【解决方案1】:

如果 targetDistance 是浮点数,则需要先将其转换为字符串,然后才能将其与另一个字符串连接。例如:

auto result = std::to_string(targetDistance) + "a";

【讨论】:

  • OP 注意:auto 告诉编译器猜测类型。在这种情况下std::string被猜到了,所以相当于写std::string result = ...;
  • 收到此错误消息'to_string' is not a member of 'std
  • @HolyBlackCat 猜测 -> 在 5 分钟结束前推断?
  • @strilz • std::to_string&lt;string&gt; 中声明,并且您需要处于C++11 编译模式或更高版本(我的程序使用C++17 编译模式)。如何指定要编译的 C++ 标准因编译器而异。
  • @HolyBlackCat • 猜测 -> 推断
【解决方案2】:

这个想法是将浮点变量(在本例中为 targetDistance)转换为字符串。 确保您已包含此标头:

#include <string>

以下代码:

string s; //to store our float variable
s= to_string( targetDistance ); //to_string function converts into string 
s= s+ "a";

这只是它的简短版本:

string s = to_string( targetDistance ) + "a" ;

【讨论】:

  • string -> std::string
最近更新 更多