5

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

}
4

3 回答 3

4

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

if (test[0] == '<') ...
于 2010-02-07T06:16:39.817 回答
2

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

char test[2];   
for (int i=0; i<amountRead; ++i)
{
    test[0] = str[i];
    test[1] = '\0'; //you could do this before the loop 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;
    }
}
于 2010-02-07T06:13:09.043 回答
1

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

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

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

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

于 2010-02-07T06:34:11.330 回答