Karolina Dobija
Karolina Dobija

Reputation: 1

While loop not breaking when it should

For some reason the while loop only ends when the end of the string has been reached.

while (s.charAt(i) != '_' || s.charAt(i) != ' ') {
  Serial.println(s.charAt(i));
  Next_Char += s.charAt(i);
  i ++;
  Serial.println(Next_Char);
  Serial.println(i);
  if (i == s.length()) {
    break;
  }
}

Upvotes: 0

Views: 95

Answers (1)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

while (s.charAt(i) != '_' || s.charAt(i) != ' ') condition will always fulfill. I think it should be while (s.charAt(i) != '_' && s.charAt(i) != ' ')

For example, suppose s.charAt(i)='_' here your first condition is now false but your second condition s.charAt(i)!=' ' this became true so loop will continue even when first condition is false. Hence while loop only ends when the end of the string has been reached.

Upvotes: 1

Related Questions