【发布时间】:2020-11-21 17:37:42
【问题描述】:
我是 C++ 新手,这个问题可能对很多人来说似乎微不足道,但请记住,我刚刚开始学习 C++ 语言。
我已将变量 x 分配为等于 20 并希望将其与字符串连接。我的 C++ 代码如下。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
int x = 20;
int y = 15;
if (x >= y) {
cout << x + " is greater than " + y;
}
}
我的预期结果是20 is greater than 15,但结果却是一些奇怪的é@。我很困惑,在 GeeksForGeeks、w3schools 或其他 SO 上找不到解决方案。
我知道使用cout << x << " is greater than " << y; 可以正常工作,但我不确定为什么连接在这里不起作用。还有,为什么会出现这些奇怪的字符呢?
提前致谢。
(另外,请不要在没有回答问题的情况下留下答案。我记得在启动 JS 时我问了一个问题,唯一的答案是“不要使用document.write。”虽然我明白了,但它会是更好地回答这个问题并将其作为旁注。)
【问题讨论】:
-
提示:数字加字符串未定义。在 C++ 中,这一切都是通过
operator+定义完成的。其他语言在字符串和数字之间任意转换。 C++ 一般不会。 -
进一步提示:std::to_string。 en.cppreference.com/w/cpp/string/basic_string/to_string
-
float + int 已定义,并触发转换。 string + other things 不是串联,不会触发转换。在 C++ 中不要假设类型转换会自动发生
-
你可以试试
std::to_string(x) + " is greater than " + std::to_string(y)让它工作。 -
更好的提示:数字+字符串是定义的,但不是你想的那样。
标签: c++ string int concatenation