将字符数组中的字符与 strcmp 进行比较

2022-01-25 00:00:00 compare c++ chars

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

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

知道发生了什么吗?

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;
    }

}

推荐答案

你需要 0 终止你的测试字符串.

you need to 0 terminate your test string.

char test[2];   
for (int i=0; i<amountRead; ++i)
{
    test[0] = str[i];
    test[1] = ''; //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

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

相关文章