首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >char和const char的区别

char和const char的区别
EN

Stack Overflow用户
提问于 2016-10-06 02:31:17
回答 2查看 792关注 0票数 0
代码语言:javascript
复制
 # 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从'char‘到'const char*’-fpermissive的转换无效时出现C:\Users\DELL\Documents\cac.cpp错误

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

EN

回答 2

Stack Overflow用户

发布于 2016-10-06 02:46:33

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

strcmp需要两个字符数组。

op是一个由10个字符组成的数组。好:这正是strcmp所期望的。

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

您可以将p从单个字符'+‘更改为字符数组"+",或者只比较op的第0个字符,如上面的注释所建议的那样。

票数 2
EN

Stack Overflow用户

发布于 2016-10-06 02:59:25

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

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

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39881312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档