So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By Wim7
#95229 Hello,
I can't get my code to function correctly. I have char[]'s and string and pointer stuff mixed up.
I want to copy a String tmpstr into a String lastline. The tmpstr is correct. It shows on the USB and is written into a file on SDcard. But the webserver (and the extra debug prints inbetween) show the copied lastline is not correct.
Code: Select all..
char inbuf[20]; // 0..19
..
bool avail = false;
String lastline = "hallo";
..
..


void setup() {
.. 
  for (int ii=0; ii<lastline.length(); Serial.write(lastline.charAt(ii++)));
  Serial.println("");
  Serial.println("System configured. Start loop");
} // setup()


void loop() {
  Ds1302::DateTime now;
..
  if (avail)
  {
    int ii;
    String tmpstr = "";
         
    rtc.getDateTime(&now);  // get the current time
    tmpstr = "20";
..
..
    tmpstr += (now.second);  // 00-59
    tmpstr += "_";
    for (ii=1; ii<5; tmpstr += inbuf[ii++]);  // 4 chars, i.e "!123"
    Serial.println(tmpstr);
    Serial.printf("[%s]\n\r",tmpstr); 
    Serial.printf("Length= %i, [23]= %c \n\r", tmpstr.length(), tmpstr[23]);
// following code is not correct
    lastline = "";
    for (ii=0; ii<tmpstr.length(); lastline += tmpstr[ii++]);
    for (ii=0; ii<tmpstr.length(); Serial.write(lastline[ii++]));
    Serial.printf("\r\nlastline=[%s] length=%i.\n\r", lastline, lastline.length());
..
    Serial.println("geschreven");
    avail = false;
  } // end avail

..
} // loop()



USB Serial output shows:
Code: Select all..
hallo
System configured. Start loop

2022-09-06 13:46:47_!030
[⸮⸮?]

Length= 24, [23]= 0

2022-09-06 13:46:47_!030
lastline=[⸮⸮?] length=24.

geschreven
2022-09-06 13:46:59_!041
[T⸮?]

Length= 24, [23]= 1

2022-09-06 13:46:59_!041
lastline=[T⸮?] length=24.

geschreven


What is the correct code to copy tmpstr into lastline?

Thanxs
User avatar
By davydnorris
#95253 String is an object so if you say something like

Code: Select allString blah = "hi there";


you're assigning it to point to a constant. If you want to be able to do string operators on it you have to make it an object instead, by using

Code: Select allString blah = String("hi there");


Then you should be able to do what you need to do
User avatar
By Wim7
#95254 Thenx davydnorris

I used this code a 'workaround' to continue
Code: Select allchar lasttime[30];
..
void loop() {
String tmpstr = "";
..
    for (ii=0; ii<tmpstr.length(); ii++) lasttime[ii] = char(tmpstr[ii]);
    lasttime[ii] = '0';
..


this allowed me to :
snprintf(temp, 400,
..
&lasttime[0]
..etc