char和const char之间的区别

时间:2016-10-05 18:31:17

标签: c++

 # include <iostream>
# include <string.h>
using namespace std;
int main()
{
    int a=10;
    int b=20;
    char op[10];
    const char p='+';
    cout<<"enter the operation"<<endl;
    cin>>op;
    if(!strcmp(op,p)==0)
{
        cout<<a+b;
}
    return 0;
}

编译结果

12 17 C:\ Users \ DELL \ Documents \ cac.cpp [错误]来自&#39; char&#39;的无效转换到#char; char *&#39; [-fpermissive]

我是初学者。请告诉我我做错了什么。

2 个答案:

答案 0 :(得分:2)

这不是charconst char之间的区别,而是char []char之间的区别。

strcmp需要两个字符数组。

op是一个包含(10)个字符的数组。好:那是strcmp所期望的。

p是一个单一字符。不好:strcmp需要一个char数组,而p不是任何类型的数组,而是单个字符。

您可以从单个字符更改p&#39; +&#39;到char数组&#34; +&#34;,或只比较op的第0个字符,如上面的评论所示。

答案 1 :(得分:0)

没有版本的strcmp将单个字符作为参数,而是需要两个字符串并对它们进行比较。

如果要将单个char变量与字符串进行比较,可以将其与字符串的第一个元素或任何其他元素进行比较:

#include <iostream>
#include <string>


int main()
{

    char op[10]  = "Hi";
    const char p = '+';

   // if( strcmp( op, p) ) // error cannot covert parameter 2 from char to const char*
   //    cout << "op and p are identic" << std::endl;
   // else
   //    std::cout << "op and b are not identic" << std::endl;

    if(op[0] == p)
        std::cout << "op[0] and p are identic" << std::endl;
    else
        std::cout << "op[0] and p are not identic" << std::endl;

    const char* const pStr  = "Bye"; //constant pointer to constant character string: pStr cannot change neither the address nor the value in address
    const char* const pStr2 = "bye"; // the same as above

    // pStr++; //error
    // pStr[0]++; // error 


    if( !strcmp( pStr, pStr2) )
        std::cout << "pStr and pStr2 are identic" << std::endl;
    else
        std::cout << "pStr and pStr2 are Not identic" << std::endl;

    return 0;
}