char c = str[i].c_str(); returns an error. Why ?

Hello !

I am trying to write char by char to Serial:

String str = "SET detectionDirection 0";
char c;
for(int i=0; i<str.length(); i++) {
  c = str[i].c_str();
  USE_SERIAL1.write(c);
}

and

c = str[i].c_str();

returns

src/main.cpp:827:32: error: request for member 'c_str' in 'str.String::operator[](((unsigned int)i))', which is of non-class type 'char'

Shouldn't it work ?

If this isn't supposed to work, how can I send a String char by char to Serial ?

Two things wrong:

  • You're trying to treat your String variable 'str' as an array of String objects.

  • The c_str() method returns a char * not a char. See Wstring.h:

const char * c_str() const { return buffer; }

gfvalvo:
Two things wrong:

  • You're trying to treat your String variable 'str' as an array of String objects.

  • The c_str() method returns a char * not a char. See Wstring.h:

const char * c_str() const { return buffer; }

And how do I fix it ?
How can I write SET detectionDirection 0 char by char to Serial ?

write also uses const char *:

inline size_t write(const char * s)
char str[] = "SET detectionDirection 0";
for(int i=0; i<strlen(str); i++) {
  USE_SERIAL1.write(str[i]);
}

GeorgeFlorian:
I am trying to write char by char to Serial:

Why do you want to do that? The write() method can take the whole thing and do the looping by itself. Modifying @jremington's example:

  char str[] = "SET detectionDirection 0";
  USE_SERIAL1.write(str, strlen(str));

Of course, since you'd be sending a c-string, you can just use the print() method:

  char str[] = "SET detectionDirection 0";
  USE_SERIAL1.print(str);