Comparing strings with strcmp

I am trying to sort an array of strings so I thought of using the strcmp BUT I am getting a syntax error on this line

if(strcmp(names[0], names[1]) < 0)

The error is
16 C:\Dev-Cpp\ifTest.cpp no matching function for call to `strcmp(std::string&, std::string&)' and
C:\Dev-Cpp\include\string.h:43 candidates are: int strcmp(const char*, const char*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main()
{
 string names[5]={"Marsh, alan", "turtle, tami", "booby, google",
                   "turner, ted", "rodgers, mimi"};
 int ages [5]={10,20,30,40,50};
 string * strPtr[5];

 
  if(strcmp(names[0], names[1]) < 0)
   cout << "name 0 is first " << endl;
   
 return 0;
}


if you're using std::string, you don't need strcmp, you can just use <. strcmp is for c-style strings (char arrays)

1
2
if(names[0] < names[1])
  cout << "name 0 is first " << endl;
Last edited on
Or you can use: http://www.cplusplus.com/reference/string/string/compare/

Remember to remove the cstring header.
Thanks! that was driving me nuts.
Topic archived. No new replies allowed.