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

时间:2018-02-18 00:16:36

标签: c++

窥视。我是个菜鸟。我有一个问题要问,但下面是我的代码。

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;
}

基本上我的程序所做的是输入一个数字&#39; a&#39;并检查它是否为数字,如果是,则使用&#34; switch case&#34;指导我2个选项。

问题:它向我显示了这个奇怪的错误 &#34;错误:类型的无效操作数&#39; const char &#39;和&#39; const char [28]&#39;二进制&#39;运算符+&#39;&#34; ,我不知道它意味着什么。它在第16,23和25行弹出了这个错误,并且我将这些行标记为星号,以便您可以看到错误出现的位置。谢谢,如果你能帮助我的话!

编辑:我的问题 WAS 错误是什么?为什么我的程序不起作用?我 意识到 我做了+ b而不是&lt;&lt; &#34; +&#34; &LT;&LT;湾我在编码方面一直在研究2-3种语言,但我犯了一个错误。就在1天前,我甚至说我的问题得到了回答。谢谢。

顺便说一句:程序在切换案例之前工作得很好!大声笑 编辑:问题解决了。

1 个答案:

答案 0 :(得分:2)

该行

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;

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