1

For const string reference variable str in the following piece of code:

Works well: for(int i=0; str[i]; i++)

Throws error: for(int i=0; *(str+i); i++)

Error: error: no match for 'operator+' (operand types are 'const string {aka const std::basic_string}' and 'int')

// Return true if str is binary, else false
bool isBinary(const string &str)
{
   for(int i=0; *(str+i); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
   }
   return true;
}

P.S.: I can understand this might be a naive question, but then I would be happy to be redirected to useful sources too!

Garf365
  • 3,619
  • 5
  • 29
  • 41
devautor
  • 2,506
  • 4
  • 21
  • 31

1 Answers1

2

str is of type std::string, it is not char*, and there is no operator+(int) defined for it, what you can do is to get its size with length member function:

bool isBinary(const string &str)
{
   for(int i=0; i < str.length(); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
    }
    return true;
}

On the other hand, if you got a c string, you can do the second form, since c strings are just null terminated char arrays.

bool isBinary(const char *str)
{
   for(int i=0; *(str+i); i++){
       if(str[i]!='0' && str[i]!='1')
           return false;
    }
    return true;
}

Also, you could get c string from c++'s std::string with its c_str() member function.

const char *s = str.c_str();
fluter
  • 13,238
  • 8
  • 62
  • 100