Go Down

Topic: String comparison not working (Read 872 times) previous topic - next topic

Mecatronicsstudent

I am trying to compare a string to a series of letters.  My code uploads and it will store the a and b I type in, but will not print equal when I type in three a. I am new to using strings so it could be an obvious problem. Any help would be very appreciated.

String charStorage;
int inByte = 0;
void setup(){
  Serial.begin(9600);
}
void loop(){
  if (Serial.available() > 0) {
   int inByte = Serial.read();
   switch(inByte){
     case 'a' :
     charStorage += 'a';
     Serial.println(charStorage);
     break;
     case 'b' :
     charStorage += 'b';
     Serial.println(charStorage);
     break;
if(charStorage == "aaa" ){
Serial.println("equal");
}
  }
}
}

el_supremo

Use Tools|Auto Format in the IDE to straighten out your code. You will then perhaps see that the if statement isn't in the right place.

Pete

dkl65

Take the if statement out of the switch statement.

Mecatronicsstudent

Thank you. That fixed it. This is helpful.

James C4S

You really should be using strcmp() to compare strings, not ==.
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

AWOL

Quote
You really should be using strcmp() to compare strings, not ==.

But s/he is using Strings, not strings, so == is fine.

(Does the String class even have a "strcmp" method?)
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

PaulS

Quote
Does the String class even have a "strcmp" method?

No, but OP should learn how to NOT use the String class. It's a damned resource hog, and provides little value in such a trivial program.

AWOL

I can't disagree, but if the question relates to the String class, I feel we should respond in like.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up