lundi 24 septembre 2018

Compare string byte against char c++

What I want is to iterate through a string, and for each of the characters in this string, compare it against a certain character, for example "M". std::string::find won't work for me as the order in which the characters appear in the string matters (e.g. in roman numerals MC is different to CM).

The code I've got (I'm compiling with c++11):

#include <iostream>
#include <cstring>
using namespace std;


int main ()
{
  string str = ("Test Mstring");
  for (auto it = str.begin(); it < str.end(); it++) {
    if (strcmp(*it, "M") == 0) cout << "M!1!!1!" << endl;
  }
}

The console error display:

test.cc: In function ‘int main()’:
test.cc:10:16: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
     if (strcmp(*it, "M") == 0) cout << "M!1!!1!" << endl;
                ^~~
In file included from /usr/include/c++/7/cstring:42:0,
                 from test.cc:2:
/usr/include/string.h:136:12: note:   initializing argument 1 of ‘int strcmp(const char*, const char*)’
 extern int strcmp (const char *__s1, const char *__s2)

Aucun commentaire:

Enregistrer un commentaire