Reputation: 11
What I want to do is very very simple. Read through a string character by character and write the numbers to a separate string while including a space in between.
Ex. original string: "45+67-32" becomes "45 67 32"
Here's my logic:
while (i < line.length())
{
char c = line.at(i);
if (isdigit(c))
{
c = line.at(i);
while (isdigit(c) || c == '.' && i < line.size())
{
expression = expression + line.at(i);
i++;
}
expression = expression + ' ';
}
i++;
}
Upvotes: 1
Views: 98
Reputation: 22176
C++ standard mandates a feature called short-circuiting. If a result of logical operation can be determined without evaluating all of the operands, it should be done so. There are two cases when this happens:
a || b
(a or b), if a
is true
then expression must also be true
and b
is irrelevant,a && b
(a and b), if a
is false
then expression must also be false
and b
is irrelevant.Because of short circuits, c == '.' && i < line.size()
is not evaluated as long as isdigit(c)
is true
. Therefore you never know if you are already outside of the string or not.
You can fix your loop by using short circuits to your advantege:
while (i < line.size() && (isdigit(c) || c == '.'))
Upvotes: 1