[英]difference between char and const char
# 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 [错误]从'char'到'const char *'的无效转换[-fpermissive]
我是初学者。 请告诉我我犯了什么错误。
这不是关于char
和const char
之间的区别,而是关于char []
和char
之间的区别。
strcmp
需要两个字符数组。
op
是(10)个字符的数组。 好:这是strcmp
期望的。
p
是单个字符。 不好: strcmp
需要一个char数组,而p
不是任何类型的数组,而是一个字符。
您可以将p
从单个char'+'更改为char数组“ +”,或者仅比较op
的第0个字符,如上面的注释中所建议。
没有任何采用单个字符作为参数的strcmp版本,而是采用两个字符串进行比较。
如果要将单个char变量与字符串进行比较,则可以将其与string的第一个元素或任何其他元素进行比较:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.