Read String and compare

I try to read from serial a String and compare it to a word.
I tried several method and I did not succeed.
What did I miss?

String answer;
String answer1= "answer1";
String SR="";

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

void loop() 
{
  Serial.println("a question with 3 answers");
  while(!Serial.available()){}
  //answer= Serial.readString(); //Trying this method instead of the function
  answer= StringRead();
  Serial.println("Checkpoint 2:" + answer);
  
  if (answer.equals(answer1)) //Trying this method
  {
    Serial.println("answer 1 is correct");
  }
  else if (answer== "answer2")
  {
    Serial.println("answer 2 is correct");
  }
  else if (answer== "answer3")
  {
    Serial.println("answer 3 is correct");
  }
  else
  {
    Serial.println("wrong");
  }
}

String StringRead()
{
  SR="";
  while (Serial.available()) {
    delay(5);
    char c = Serial.read();
    SR += c;
  }

  if (SR.length() >0) {
    Serial.println("Checkpoint:" + SR);// Checkpoint
    return SR;
  }
}

I read and checked:

https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringComparisonOperators
https://forum.arduino.cc/index.php?topic=162465.0

But I could not find an answer. :frowning:

What is the serial monitor line ending?

TheMemberFormerlyKnownAsAWOL:
What is the serial monitor line ending?

You mean the void loop?
If so I will continue it after I solve this problem.

No, I mean '“at the bottom of the serial monitor there is a control labelled “line ending” - what is it set to?”

TheMemberFormerlyKnownAsAWOL:
No, I mean '"at the bottom of the serial monitor there is a control labelled "line ending" - what is it set to?"

Sorry, I only started messing around with Arduino a few weeks ago.
it is no "both NL & CR"

Set it to “none”.

Retest and report back.

TheMemberFormerlyKnownAsAWOL:
Set it to “none”.

Retest and report back.

Thanks it worked,
Thank you

Can you explain to me why?

Because the Strings you were receiving contained the carriage-return and line-feed characters, but you were not testing for them, so your Strings were never equal.

Set it to "none".

In my IDE 1.8.13, there is no "none" option for "Line ending tab".

GolamMostafa:
In my IDE 1.8.13, there is no “none” option for “Line ending tab”.

Yeah, whatever.
I don’t use the serial monitor often enough to remember exactly what the settings are.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.