字符串字面量之间的比较 [英] comparison between string literal

查看:154
本文介绍了字符串字面量之间的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个非常简单的代码:

#include <iostream>

using namespace std;

void exec(char* option)
{
    cout << "option is " << option << endl;
    if (option == "foo")
        cout << "option foo";
    else if (option == "bar")
        cout << "opzion bar";
    else
        cout << "???";
    cout << endl;
}

int main()
{
    char opt[] = "foo";
    exec(opt);
    return 0;
}

生成两个警告:与未指定行为的字符串文字结果进行比较。

generate two warning: comparison with string literal results in unspecified behaviour.

您能解释为什么这个代码不起作用,但如果我改变

Can you explain why exactly this code doesn't work, but if I change

char opt[]

char *opt

它可以工作,但会产生警告?它是否与\0终止相关?两个声明的opt之间有什么区别?如果我使用const限定符怎么办?解决方案是使用std :: string?

it works, but generates the warning? Is it related to the \0 termination? What is the difference between the two declaration of opt? What if I use const qualifier? The solution is to use std::string?

推荐答案

char数组或字符指针不是真正的字符串类对象在C ++中,因此

char arrays or char pointers aren't really the same thing as string class objects in C++, so this

if (option == "foo")

不会将字符串选项与字符串文字foo 选项的 地址。如果您想知道该选项是否与foo相同,则需要使用许多字符串比较函数之一。 strcmp 是显而易见的方法,或者您可以使用 std :: string ,而不是 char *

Doesn't compare the string option to the string literal "foo" it compares the address of option with the address of the string literal "foo". You need to use one of the many string comparison functions if you want to know if the option is the same as "foo". strcmp is the obvious way to do this, or you can use std::string instead of char*

这篇关于字符串字面量之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆