Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No matching function for call to strcmp

Tags:

c++

I am new to c++ and currently am facing an error while using strcmp.

I have defined a structure as follows:

struct student
{
 string name;
 int roll;
 float marks;
 dob dobi;
 string dobp;
};
student *p;

And then, I am passing the pointer inside a function to sort it, like this:

void sortData(student *p)
{
 int a=0,b=0;
 for (a=0; a<=arraySize; a++)
 {
    for (b=a; b<=arraySize; b++)
    {
        if( strcmp(p[a].name, p[b].name) > 0 ) //Error
        {
           //sort logic yet to be implemented 
        }
    }
 }
}

Can someone please point out the mistake.

Error Message:

No matching function for call to strcmp

like image 739
Panda Avatar asked Feb 13 '16 05:02

Panda


People also ask

What can I use instead of strcmp?

With string arrays, you can use relational operators ( == , ~= , < , > , <= , >= ) instead of strcmp . You can compare and sort string arrays just as you can with numeric arrays.

Can you use strcmp with a string?

Threadsafe: Yes. The strcmp() function compares string1 and string2 . The function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.

Can strcmp return null?

Output -1: MySQL STRCMP() function returns -1 if the first string is smaller than the second string. Output NULL: MySQL STRCMP() function returns NULL if any one or both of the argument of STRCMP() function is NULL.

How can I compare two characters in C++?

String strcmp() function in C++ In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same.


2 Answers

strcmp takes two const char*s for input - you need to convert your strings to C-style strings (assuming you're using std::string) using std::string::c_str():

if (strcmp(p[a].name.c_str(), p[b].name.c_str()) > 0)
//                  ^ Here             ^ and here
like image 76
Levi Avatar answered Oct 05 '22 17:10

Levi


std::strcmp takes const char* as its parameter, while std::string doesn't match directly.

Because you're using std::string, you can just use operator>(std::basic_string)

if (p[a].name > p[b].name)

or use std::basic_string::compare

if (p[a].name.compare(p[b].name) > 0)
like image 21
songyuanyao Avatar answered Oct 05 '22 17:10

songyuanyao