将字符数组中的字符与 strcmp 进行比较 [英] Comparing chars in a character array with strcmp

查看:23
本文介绍了将字符数组中的字符与 strcmp 进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 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;
    }
}

这篇关于将字符数组中的字符与 strcmp 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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