C++ 使用 strcmp 比较字符数组中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2216143/
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 22:35:00  来源:igfitidea点击:

Comparing chars in a character array with strcmp

c++comparechars

提问by Isawpalmetto

I have read an xml file into a char [] and am trying to compare each element in that array with certain chars, such as "<" and ">". The char array "test" is just an array of one element and contains the character to be compared (i had to do it like this or the strcmp method would give me an error about converting char to cons char*). However, something is wrong and I can not figure it out. Here is what I am getting:
< is being compared to: < strcmp value: 44

我已将 xml 文件读入 char [] 并尝试将该数组中的每个元素与某些字符(例如“<”和“>”)进行比较。char 数组“test”只是一个包含一个元素的数组,包含要比较的字符(我必须这样做,否则 strcmp 方法会给我一个关于将 char 转换为 cons char* 的错误)。但是,出了点问题,我无法弄清楚。这是我得到的:
< 正在与:< strcmp 值:44

Any idea what is happening?

知道发生了什么吗?

char test[1];   
for (int i=0; i<amountRead; ++i)
{
    test[0] = str[i];
    if( strcmp(test, "<") == 0)
        cout<<"They are equal"<<endl;
    else
    {
        cout<<test[0]<< " is being compare to: "<<str[i]<<" strcmp value= "<<strcmp(test, "<") <<endl;
    }

}

采纳答案by John Knoeller

you need to 0 terminate your test string.

您需要 0 终止您的测试字符串。

char test[2];   
for (int i=0; i<amountRead; ++i)
{
    test[0] = str[i];
    test[1] = '
for (int i=0; i<amountRead; ++i)
{
    if (str[i] == "<")
       cout<<"They are equal"<<endl;
    else
    {
        cout << str[i] << " is being compare to: <" << endl;
    }
}
'; //you could do this before the loop instead. ...

But if you always intend to compare one character at a time, then the temp buffer isn't necessary at all. You could do this instead

但是,如果您总是打算一次比较一个字符,则根本不需要临时缓冲区。你可以这样做

if (test[0] == '<') ...

回答by Michael Burr

strcmp()expects both of its parameters to be null terminated strings, not simple characters. If you want to compare characters for equality, you don't need to call a function, just compare the characters:

strcmp()期望它的两个参数都是以空字符结尾的字符串,而不是简单的字符。如果要比较字符是否相等,则不需要调用函数,只需比较字符即可:

if( strncmp(test, "<", 1) == 0 )

回答by R Samuel Klatchko

strcmp wants both strings to be 0 terminated.

strcmp 希望两个字符串都以 0 结尾。

When you have non-0 terminated strings, use strncmp:

当您有非 0 终止的字符串时,请使用strncmp

##代码##

It is up to you to make sure that both strings are at least N characters long (where N is the value of the 3rd parameter). strncmp is a good functions to have in your mental toolkit.

您需要确保两个字符串的长度至少为 N 个字符(其中 N 是第三个参数的值)。strncmp 是您心理工具包中的一个很好的功能。