使用 strcmp 比较字符数组中的字符
我已将 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;
}
}
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
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strcmp()
期望其两个参数都是以 null 结尾的字符串,而不是简单字符。如果要比较字符是否相等,则不需要调用函数,只需比较字符即可: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:您需要 0 终止您的测试字符串。
但是,如果您总是打算一次比较一个字符,则根本不需要临时缓冲区。你可以这样做
you need to 0 terminate your test string.
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
strcmp 希望两个字符串都以 0 结尾。
当您有非 0 结尾的字符串时,请使用 strncmp
:由您来确保两个字符串的长度至少为 N 个字符(其中 N 是第三个参数的值)。 strncmp 是您心理工具箱中的一个很好的函数。
strcmp wants both strings to be 0 terminated.
When you have non-0 terminated strings, use 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.