简体   繁体   English

即使比较在相同的字符串之间,strcmp()也会返回错误的值

[英]strcmp() returns wrong value even when the comparison is between same strings

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
    string x;
    cin>>x;

    if(strcmp(&x.at(0), "M") == 0)
    {
        cout<<"midget ";
    }
    else if(strcmp(&x.at(0), "J") == 0)
    {
        cout<<"junior ";
    }
    else if(strcmp(&x.at(0), "S") == 0)
    {
        cout<<"senior ";
    }
    else
    {
        cout<<"invalid code";
    }

    if(strcmp(&x.at(1), "B") == 0)
    {
        cout<<"boys";
    }
    else
    {
        cout<<"girls";
    }
    return 0;
}

I've used the above code to compare MB which should return "midget boys" but it keeps falling to else and returns "invalid codeboys". 我已经使用上面的代码来比较MB应该返回“侏儒男孩”,但它继续下降到其他并返回“无效的codeboys”。 Somehow the second condition works fine. 不知何故第二个条件正常。 My diagnostics tell me that at the first comparison it returns 66 . 我的诊断告诉我,在第一次比较时,它返回66 I guess that is the ASCII code for "M". 我猜这是“M”的ASCII代码。 But how do I solve my problem now? 但是我现在如何解决我的问题呢?

strcmp expects to compare two null-terminated strings. strcmp期望比较两个以null结尾的字符串。 It will start comparing the first character of each string. 它将开始比较每个字符串的第一个字符。 If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. 如果它们彼此相等,则继续使用以下对,直到字符不同或直到达到终止空字符。

You want to compare two chars. 你想比较两个字符。 Try this: 尝试这个:

if(x.at(0) == 'M')
...

When interpreted as a C-style string &x.at(0) is actually equivalent to x.c_str() : both of these return a pointer to the first character in the string. 当解释为C风格的字符串时&x.at(0)实际上等同于x.c_str() :它们都返回指向字符串中第一个字符的指针。 Functions like strcmp , which operate on C-style strings, will determine the string length by reading until the first null character. strcmp这样的函数在C风格的字符串上运行,它将通过读取直到第一个空字符来确定字符串长度。

Thus, in your example, your first test compares "MB" with "M". 因此,在您的示例中,您的第一个测试将“MB”与“M”进行比较。

Your test for the second character works of course, because the "B" is immediately followed by the null delimiter. 您对第二个字符的测试当然是有效的,因为“B”后面紧跟着空分隔符。

As others have already said, you can do what you need via a direct char comparison: x.at(0) == 'M' 正如其他人已经说过的那样,你可以通过直接的char比较来做你需要的: x.at(0) == 'M'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM