0

I am trying to compare two string but each time i am getting awkward results. When i use Equals() function i always get the wrong answer and never satisfy the IF statement. When i use compareTo() function i always get the right answer (which is btw not correct) but it always just satisfy the IF statement.

String input;
String Answer = "cat";

void setup()
{
  Serial.begin(19200);
}

void loop()
{
  while (Serial.available() == 0)
  {
    Serial.readStringUntil('\n');
    if (input.equals(Answer))
    {
      Serial.println(input + ", Correct");
    }
    else
    {
      Serial.println(input + ", wrong");
    }
  }
}

Above is the code i am using to learn the string Comparison.

0

1 Answer 1

1

You have defined a variable named input, but you never assign a value to it. It should thus always have its initial value, which is an empty string.

Here:

Serial.readStringUntil('\n');

you probably meant

input = Serial.readStringUntil('\n');
2
  • Edgar Bonet thanks. I have initialised the input as you mentioned. But results are same. I don't know what's getting wrong here. Commented Apr 12, 2022 at 19:52
  • @ASADALI, add input.trim() after input = Serial.readStringUntil('\n'); to remove \r Commented Apr 13, 2022 at 4:52

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.