-->
Page 1 of 1

Converting a string to Array

PostPosted: Tue Jan 15, 2019 2:04 am
by sahebdatta
Incorrect result on using toCharArray() or converting a string to array manually

Hi,

I'm using NodeMCU for a project and Arduino 1.8.8. I want to convert a string to char Array. The code and output are as follows.

code:
Code: Select allchar ssid[] = "";
char pass[] = "";
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  String answer = "ssid:Moto G (4) 6788aesrhtd5@#$; pass:error$34556jjhjv24";
  extract(answer);
  Serial.println(ssid);
  Serial.println(pass);
}

void extract(String value) {
  String t_ssid = "";
  String t_pass = "";
  int flag = 0;
  int len = value.length();
  for (int i = 0; i < len ; i++) {
    if (value.charAt(i) == ';')
      flag = i;
  }
  t_ssid = value.substring(5, flag);
  t_pass = value.substring(flag + 7, len);
  Serial.print(ssid);
  Serial.println(".");
  Serial.print(pass);
  Serial.println(".");
  Serial.println();
  Serial.println(t_ssid);
  Serial.println(t_pass);
  for (int i = 0; i < t_ssid.length(); i++)
    ssid[i] = t_ssid.charAt(i);
  for (int j = 0; j < t_pass.length(); j++)
    pass[j] = t_pass.charAt(j);
}

void loop() {
  // put your main code here, to run repeatedly:

}


Result:
Screenshot attached herewith. (I've pressed the reset button once.)

Expected Result:
Code: Select all
.
.
Moto G (4) 6788aesrhtd5@#$
error$34556jjhjv24

Moto G (4) 6788aesrhtd5@#$
error$34556jjhjv24


I'm pretty much unsure as of why the result is not as expected and also why these ghostly characters are showing up in the serial monitor.

Any help is highly appreciated...