C++:"错误:类型'const char*'和'const char [28]'的操作数无效到二进制'ope

C++: "error: invalid operands of types 'const char*' and 'const char [28]' to binary 'operator+'"

本文关键字:const char 操作数 无效 ope 二进制 错误 quot 类型 C++      更新时间:2023-10-16

Peeps.我是菜鸟。我有一个问题要问,但这是我下面的代码。

int main() {
int a, c, favNum;
favNum = 3;
cout << "Hello! Please enter a number in the space below. This number will be called 'a'. " << endl;
cout << "Enter:  " << endl;
cin >> a;

if ( typeid(a) == typeid(int) && cin.fail()==false){
cout << "Great Job!" << endl;
cout << "Let's do cool stuff with this program! " << endl;
* cout << "Type '1' for checking whether your number, " + a + ", is a 
number divisible by," + favNum + "." << endl;
cout << "Type '2' to recieve a compliment " << endl;
cin >> c;
switch (c) {
case 1:
cout << "Awesome!" << endl;
if( a%favNum == 0 ){
*   cout << "Your 'a' number, " +a+ ", is a number divisible by 
'favNum'," +favNum+ "." << endl;
} else if (a%favNum != 0){
*   cout << "Your 'a' number, " +a+ ", is a number not divisible by 
'favNum'," +favNum+ "." << endl;
}
break();
case 2:
cout << "Great Job!" << endl;
}
} else {
cout << "Oops.. Might wanna try to write a number. Doesn't look like a 
number to me.." << endl;
cout << "Please restart your program and follow instructions next 
time." 
<< endl;
}

基本上我的程序所做的是输入一个数字"a",并检查它是否是一个数字,如果是,它使用"切换大小写"将我定向到 2 个选项。

问题:它向我展示了这个奇怪的错误"错误:类型'constchar'和'const char [28]'到二进制'operator+'的无效操作数">,我不知道这是什么意思。它在第 16、23 和 25 行上弹出了此错误,我在行中加了星号,以便您可以看到错误出现的位置。谢谢,如果你能帮助我!

编辑:我的问题是什么错误? 以及为什么我的程序不起作用?我意识到我做了一个 + b 而不是一个<<"+"<<b。我一直在编码中使用 2-3 种语言,但我犯了一个错误。就在1天前,我什至说我的问题得到了回答。谢谢。

顺便说一句:程序在开关盒之前工作得很好!大声笑 编辑:问题已解决。

cout << "Type '1' for checking whether your number, " + a +
", is a number divisible by," + favNum + "." << endl;

由于以下原因不起作用:

"Type '1' for checking whether your number, " + a没有做你希望它能做的事情。

该行等效于:

const char* cp1 = "Type '1' for checking whether your number, ";
const char* cp2 = cp1 + a; // Depending on the value of a, cp2 points
// to something in the middle of cp1 or something
// beyond.
cout << cp2 + ", is a number divisible by," + favNum + "." << endl;

这是一个问题,因为没有为cp2类型和+运算符后面的字符串文本定义加号运算符。来自编译器的错误消息引用了该术语。

cp2的类型是const const*
字符串文本的类型为const char[28]

您可以通过重复使用插入运算符(<<)来获得所需的内容。

cout
<< "Type '1' for checking whether your number, "
<< a
<< ", is a number divisible by,"
<< favNum 
<< "."
<< endl;

确保对遇到相同问题的其他行进行类似的更改。