Comparing chars in C++ - argument of type "char" is incompatible with parameter of type "const char *

StackOverflow https://stackoverflow.com/questions/18231443

  •  24-06-2022
  •  | 
  •  

Question

Im trying to compare 2 values in C++ (which im new to so please go easy)

struct styles{
int itemNo;
char desc[26]; 
char brand[21]; //between 3 - 20
char category;
double cost;
};  

struct declared above, then im using this code in another function

char cat[2];
for (x=0;x<size;x++)
{

    if (strcmp(cat,styleAr[x].category)==0)

its giving me an error with the 'styleAr[x].category' in the if statement: argument of type "char" is incompatible with parameter of type "const char *

any explanations on how I could solve this would be great

Was it helpful?

Solution

Assuming that cat is a string (that is, one character followed by a '\0'), then you should do this:

if (cat[0] == styleAr[x].category)

But of course, if you use std::string cat and std::string category, you can just write:

if (cat == styleAr[x].category)

OTHER TIPS

You have category as a single char and cat is an array of chars (i.e. a char *)... you probably didn't mean to compare a string with a single character

strcmp compares character arrays, but category is just a single char, hence the error. You can compare two chars directly using == If category is supposed to be a single char, you need to change the comparison code

char cat='?';//or whatever you are looking for

for (x=0;x<size;x++)
{
    if (cat == styleAr[x].category)

You're comparing a two-char array (cat), that is NOT initalized to any value (at least not in the code that you showed us), to a single char.

The strcmp function accepts two arguments of type const char*, that is two null-terminated c-style strings (a char array whose last element is a '\0' character, the null character).

If you want to compare just one character, use the following code:

char cat = ; // Put the character you want to compare styleAr[x].category against there.

for (int x = 0 ; x < size; x++)
{
    if (cat == styleAr[x].category)
    {
       // The two characters are equal.
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top