Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing chars in a character array with strcmp

Tags:

c++

compare

chars

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

}
like image 687
Isawpalmetto Avatar asked Feb 07 '10 06:02

Isawpalmetto


2 Answers

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:

if (test[0] == '<') ...
like image 75
Michael Burr Avatar answered Nov 15 '22 03:11

Michael Burr


you need to 0 terminate your test string.

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.
    ...

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;
    }
}
like image 21
John Knoeller Avatar answered Nov 15 '22 03:11

John Knoeller