MATLAB Answers


Break doesn't break out of endless loop

Asked by Hieu Philip Hoang on 14 Feb 2019
Latest activity Commented on by Walter Roberson
on 14 Feb 2019
Hey guys!
I am designing an app, where one function is to read out some strings, which are sent from an Arduino.
So basically, the Arduino will send something like
over serial. DS is the "stopper" string, so if DS is sent, the app shall stop reading over Serial.
Now, whats frustrating me, is following: My code to read out these strings is
while 1
%read out data from serial
received_stringM = fgets(app.s);
%DS is the stopper string, so if it is sent, the while loop should end
if received_stringM == "DS"
%to display the sent string in an Edit Field
app.currentdistanceEditField_2.Value = received_stringM;
This is the Edit Field, where the string is displayed to.
But exactly this is wondering me. The code is very simple, but I thought after the break command, the following lines shouldn't be executed. But obviously, even though DS is sent, it doesn't break, but is displayed.
Does anyone see any mistake in my code?
Thanks for reading and for any advices!


on 14 Feb 2019
Put a breakpoint in and debug it to see what received_stringM actually is when you think it should hit the break instruction. Generally I still use strcmp, even with strings, but as far as I am aware == should work perfectly when on a string object, unlike a char, so this should not be a problem.
You may just need to convert the output of fgets to a string:
received_stringM = string( fgets(app.s) )
I don't know if it returns a string or a char and if that is the source of the problem.
Yea, just tried it out. It seems like there is some issue in comparing received_stringM and "DS" in the if line. I tried everything out you guys told me, but none of it worked, which is really weird...
for debugging double(received_stringM)
I think you will find that it ends in 13 (carriage return) or 10 (newline) or both.

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 14 Feb 2019

fgets includes the terminator character . use fgetl instead of fgets


Sign in to comment.