如何解决如何做这样的事情:“你的号码是“+号码”在 C++ 中?
我最近开始使用 C++,从 JavaScript 开始,所以我有点困惑。
main.cpp:14:67: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’
cout << "Perfect,Now your playing with numbers up to " + range + "."
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
$ g++ main.cpp
main.cpp: In function ‘int main()’:
main.cpp:14:67: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’
cout << "Perfect,Now your playing with numbers up to " + range + "."
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
我不知道它是否有帮助,但我将在下面附上我的代码:
#include <iostream>
using namespace std;
void startGame(int random);
int generateNo(int range);
int main() {
int range;
cout << "WELCOME TO NUMBER GUESSING GAME!" << endl;
cout << "The calculator is going to generate a random number and you'll have to guess it!" << endl;
cout << "Please enter the range of numbers you want to play (ex: 10)" << endl;
cin >> range;
int solution = generateNo(range);
cout << "Perfect,Now your playing with numbers up to " + range + "."
cout << "GOOD LUCK :)" << endl;
startGame(solution);
return 0;
}
int generateNo(int range) {
return rand() % range + 1;
}
void startGame(int random) {
int inputNo;
cin >> inputNo;
for( int a = 0; ; a++) {
if(inputNo == random) {
cout << "Congrats! You've guessed the number!" << endl;
break;
} else if(inputNo > random) {
cout << "Hooolly! WHAT'S with this giant number" << endl;
startGame(random);
break;
} else {
cout << "Good number,but had your little brain considered to make it bigger!?" << endl;
startGame(random);
break;
}
}
}
解决方法
您可以将调用链接到 <<
:
cout << "Perfect,now your playing with numbers up to " << range << ".";
如果你想先构建一个字符串(这里没有理由这样做),你首先需要构建一个字符串:
std::string text = std::string{"Perfect,now ..."} + std::to_string(range) + ".";
std::cout << text;
在您的代码中,您试图添加一个带有整数的字符串文字(类型为 char[N]
)。没有 operator+
将整数连接到字符串文字。
C++ 不会在所有任意类型之间重载 +
运算符,并且在您尝试打印时不会将所有内容隐式转换为字符串。幸运的是,对于所有内置类型,您只需使用 <<
运算符将它们写入输出流(并为您自己的类型覆盖它):
cout << "Perfect,now your playing with numbers up to "
<< range // Note the use of "<<" and not of "+"
<< "."
<< "GOOD LUCK :)"
<< endl;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。