String comparison

I want to compare two lines of user input, but cannot do that ...

#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 appears. Error 1 error C2664: 'strcmp': unable to convert parameter 1 from 'std :: string' to 'const char *' c: \ users \ asad \ documents \ visual studio 2008 \ projects \ string \ string \ string.cpp 23 line

+2


a source to share


4 answers


As you use std::string

, strcmp

it is not necessary - you can just use the <

, ==

, !=

etc.



+5


a source


At your disposal:

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

#include <string>


#include <iostream>

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



You are using C ++ and therefore no need to use strcmp. In C ++, you can just use == and! = To compare two strings.

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


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

+4


a source


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

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

0


a source


Another way to do this also

result= strcmp(my_string.c_str(),my_string2.c_str());

      

0


a source







All Articles