C++ 与字符串文字比较会导致未指定的行为?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12868143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:42:27  来源:igfitidea点击:

Comparison with string literal results in unspecified behaviour?

c++

提问by user1742497

I am having a problem with the program I am trying to code. It's just a Windows console program and I am very new to C++. It's only my 4th program.

我正在尝试编写的程序有问题。它只是一个 Windows 控制台程序,我对 C++ 很陌生。这只是我的第四个程序。

The problem I am having is that when I run my program I have no errors but a lot of warnings that say "comparison with string literal results in unspecified behaviour" in the lines that I will highlight below.

我遇到的问题是,当我运行我的程序时,我没有错误,但是在我将在下面突出显示的行中,有很多警告说“与字符串文字比较导致未指定的行为”。

When the program runs instead of adding the numbers I want it to it just gives me a random huge number no matter what I put in for my inputs.

当程序运行而不是添加我想要的数字时,它只会给我一个随机的巨大数字,无论我输入什么。

Here is the code:

这是代码:

#include <iostream>

using namespace std;

int main()
{
     int hold;
     int i;
     int n;
     i = 6;
     int result;
     int * price;
     char items[100][100];

     if (items == 0)
        cout << "No items can be stored";
    else
    {
        for (n=0; n<i; n++)
        {
            cout << "Item#" << n << ": ";
            cin >> items[n];
        }
        cout <<  "\nYou Entered: \n";
        for (n=0; n<i; n++)
            cout << items[n] << ", ";

    }
    for (n=0; n<i; n++)
    {
        if (items[n] == "ab"){
        price[n] = 2650;
        }

        else if (items[n] == "ae"){
        price[n] = 1925;
        }

        else if (items[n] == "ie"){
        price[n] = 3850;
        }

        else if (items[n] == "bt"){
        price[n] = 3000;
        }

        else if (items[n] == "pd"){
        price[n] = 2850;
        }

        else if (items[n] == "ga"){
        price[n] = 2600;
        }

    }

    for (n=0; n<i; n++)
    {
    result = result + price[n];
    }

    cout << "\nTotal gold for this build: " << result;
    cin >> hold;
    return 0;
}

Any help is appreciated. There is probably something big that I've done wrong. The names in the if statements are all currently placeholders and I'll be adding a lot more if statements when I can get it to work with the bare 6 which is what it needs to work.

任何帮助表示赞赏。我可能做错了什么大事。if 语句中的名称目前都是占位符,当我可以让它与裸 6 一起工作时,我将添加更多 if 语句,这是它需要的工作。

回答by BigBoss

In C++ ==only implemented internally for primitive types and array is not a primitive type, so comparing char[100]and string literal will only compare them as 2 char*or better to say as 2 pointers and since this 2 pointers can't be equal then items[n] == "ae"can never be true, instead of this you should either use std::stringto hold string as:

在 C++ 中==仅在内部为原始类型实现,数组不是原始类型,因此比较char[100]和字符串文字只会将它们比较为 2char*或更好地说为 2 个指针,并且由于这 2 个指针不能相等,items[n] == "ae"因此永远不会为真,而不是这个,您应该使用std::string将字符串保存为:

std::string items[100];
// initialize items
if( items[n] == "ae" ) ...

or you should use strcmpto compare strings, but remeber strcmpreturn 0 for equal strings, so your code will be as:

或者您应该使用strcmp比较字符串,但请记住strcmp对于相等的字符串返回 0,因此您的代码将如下所示:

char items[100][100];
// initialize items
if( strcmp(items[n], "ae") == 0 ) ...

And one extra note is if (items == 0)is useless, since itemsallocated on stack and not in the heap!

额外的注释是if (items == 0)无用的,因为items分配在堆栈中而不是在堆中!

回答by Luchian Grigore

First, int * price;is a dangling pointer - you never initialize it. You have to do:

首先,int * price;是一个悬空指针——你永远不会初始化它。你必须要做:

int * price = new int[i];

Second, usually, idenotes an iterator index so I suggest you stick with that - so

其次,通常,i表示迭代器索引,所以我建议你坚持 - 所以

for (i=0; i<n; i++) //some more refactoring needed

Third, you need to compare char arrays using strncmpin your case.

第三,您需要比较strncmp在您的情况下使用的 char 数组。

Fourth and most important- use std::stringand std::vectorinstead. This is C++, not C.

第四也是最重要的- 使用std::stringandstd::vector代替。这是 C++,不是 C。

回答by m0skit0

You're comparing pointers, not the actual strings. Use C++ stringclass instead of char*(or check how C strings work).

您正在比较指针,而不是实际的字符串。使用 C++string类代替char*(或检查C 字符串的工作方式)。

回答by alex

Just a little thing that got me stumbling for a bit, is the difference between single and double quotes, see: Single quotes vs. double quotes in C or C++

只是让我绊了一下的一件小事,是单引号和双引号之间的区别,请参阅:单引号与 C 或 C++ 中的双引号

I was comparing the first character of a string with double quotes and not single quotes - which resulted in above's error message.

我正在将字符串的第一个字符与双引号而不是单引号进行比较 - 这导致了上面的错误消息。