0

I am trying to check whether the input string in my serial is inside my string array, but it seems like that the condition if(array[i]==inputString) does not print true.

So here is my code:

String array[4]={"hey","jude","jane"},inputString,test;
boolean stringComplete=false;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  //int store=0;
  serialEvent();
  if(stringComplete){
    Serial.println(inputString);
    for(int i=0;i<4;i++){
      Serial.println("..");
      //test=array[i];
      Serial.println(array[i]);
      if(inputString==array[i]){
        Serial.println("true");
        break;
      }
    }
  inputString="";
  stringComplete=false;
  }
   //Serial.println(store);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}
1
  • 3
    could you please change the image by actual text for the code ? Thanks.
    – Overdrivr
    Mar 6, 2016 at 9:59

1 Answer 1

1

First, you declare an array of 4 items and provide an initializer for 3. Don't know how it can even compile, maybe it is tolerated but in doubt

String [] array = {"hey","jude","jane","foo"}; 

Also, your serialEvent function appends \n to the string. Even if you receive string jane, you will compare jane from array with jane\n from serial

char inChar = (char)Serial.read();
if( inChar == '\n')
   stringComplete = true;
else
   inputString += inChar
5
  • No reason to doubt, just look it up. See paragraph 19 (the “all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration” sentence) in part 6.7.9 of the ISO/IEC N1570 C++ standard. The 4th item of String array[4] will be initialized to a null pointer if only three initializers appear. Mar 6, 2016 at 18:10
  • Thanks for the input, but then even with the sentence it's not entirely clear to me. 4th item will be initialized to nullpointer or String with empty constructor ?
    – Overdrivr
    Mar 6, 2016 at 18:37
  • The empty string (ie. String with the default constructor).
    – Nick Gammon
    Mar 6, 2016 at 20:50
  • It occurred to me after commenting that "null pointer" might be incorrect for String objects, but didn't know offhand. Mar 6, 2016 at 20:51
  • A String object isn't a pointer, so it can't contain a null pointer, per se.
    – Nick Gammon
    Mar 6, 2016 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.