2

I want to compare two user input strings, but not able to do so...

#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;

int _tmain(int argc, _TCHAR* argv0[])
{
    string my_string;
    string my_string2;
    cout<<"Enter string"<<endl;
    cin>>my_string;
    cout<<"Enter 2nd string"<<endl;
    cin>>my_string2;
    cout<<my_string<<"  "<<my_string2;
    strcmp(my_string,my_string2);
    int result;
    result= strcmp(my_string,my_string2);
    cout<<result<<endl;
    return 0;
}

This error is appearing. Error 1 error C2664: 'strcmp' : cannot convert parameter 1 from 'std::string' to 'const char *' c:\users\asad\documents\visual studio 2008\projects\string\string\string.cpp 23 String

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
user324463
  • 21
  • 1
  • 2
  • 3

4 Answers4

5

Since you're using std::string, strcmp is unnecessary -- you can just use <, ==, !=, etc.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
4

Your includes:

Since you are including standard headers, they should be in <>

#include <string>
#include <iostream>

#include with "" is generally used for your own header files, not standard header files.

You are using C++, and therefore need not use strcmp. In C++, you can simply use == & != to compare two strings.

if (my_string == my_string2) result = 0;
else result = 1;

Also, if you want to convert a string to a const char*, you can use mystring.c_str()

Sagar
  • 9,456
  • 6
  • 54
  • 96
  • To be more pedantic, the `strcmp` function applies to an array of characters terminated by a null (a.k.a. char *). If you really need to use `strcmp`, then use it with the `c_str()` method of `std::string`. – Thomas Matthews Apr 23 '10 at 21:03
  • True, should have clarified that. Thanks! – Sagar Apr 23 '10 at 22:25
0

If you want to use strcmp note that it takes different parameters than the ones you used.

http://www.cppreference.com/wiki/c/string/strcmp

Cristina
  • 1,991
  • 3
  • 17
  • 24
0

Another way to do this is also

result= strcmp(my_string.c_str(),my_string2.c_str());
Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79