nerd007
nerd007

Reputation: 45

How do you compare a string to a vector value?

How to you do a string comparison in a to a value in a vector<std::string>?

I tried str, the error is printed below.

.....

    vector<std::string> dat;
    vector<std::string> pdat;
    dat = my();
    for(int b = 2; b < dat.size(); b+=7){
    //      cout << dat[b] << " " << endl;
            if(!strcmp(dat[b], "String\n"){    // The error is here
                    pdat.push_back(dat[b]);
            }
    }

my.cpp: In function 'std::vector > ngr()':
my.cpp:53:32: error: cannot convert '__gnu_cxx::__alloc_traits > >::value_type {aka std::basic_string}' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

Upvotes: 1

Views: 8325

Answers (3)

quantdev
quantdev

Reputation: 23813

Simply use operator== on to compare an std::string and a const char* :

if(dat[b] == "String\n"){    //
    pdat.push_back(dat[b]);
}

For the record, the exact overload used here is the function template :

template< class CharT, class traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs );

strcmp (that you dont need here, and rarely need in C++) expects const char* arguments :

int strcmp( const char *lhs, const char *rhs );

So you could (but shouldn't) invoke it with th help of the c_str() member function :

if(!strcmp(dat[b].c_str(), "String\n") 
...

Upvotes: 1

John3136
John3136

Reputation: 29266

strcmp() expects 2 const char*s but dat[b] is a string, so you aren't comparing apples with apples.

You can either do

if(!strcmp(dat[b].c_str(), "String\n"){

Or

if (dat[b] == "String\n") {

The second is the more C++ approach.

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65166

std::string is compared with plain ==. This works because the == operator is overloaded to do a string comparison for std::strings.

if (dat[b] == "String\n") {

If you're dealing with C++ strings, you shouldn't need any of the str* functions from string.h, so you might as well not include it at all.

Upvotes: 4

Related Questions