c++string

String Conversion error


I made a struct of strings and every time I try and compare my strings, it says i am comparing ints and chars...but I am only comparing strings?

while(gap > 0){
      passOk=true;
      for(int i =0; i < *total-gap; i++)
         if(strcmp(individualf->firstnames[i] , individualf->firstnames[i+gap])>0){
            exchange(individualf[i], individualf[i+gap]);
            passOk = false;
         }
      if(passOk)
         gap /= 2;
   }  
}

MY complier error is: cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int strcmp(const char*, const char*)’

      if(strcmp(individualf->firstnames[i] , individualf->firstnames[i+gap])>0){

Solution

  • std::string has an operator>, use it:

    if (individualf->firstnames[i] > individualf->firstnames[i + gap])
        // stuff
    

    If for some reason you must use strcmp, then just realize that std::string is not a const char*, and use std::string::c_str() to get a pointer to the string's memory:

    if (strcmp(individualf->firstnames[i].c_str(), individualf->firstnames[i + gap].c_str()) > 0)
        // stuff