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
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.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With