Reputation: 1
I'm having trouble determining what I'm doing wrong in a portion of my code.
I'm trying to make it so that the second part of this loop returns false for when there is a portion of a string like 0w
, 1w
, or 5/
.
However, it returns false on every string entered into the function that is called.
The first portion of the loop where I specify that only certain characters are allowed works by itself, but the second portion does not work by itself.
Also, the first portion doesn't work when combined with the second portion.
I'll guess that whatever I'm doing wrong is a pretty simple fix, but I'm just not sure what it is.
Also, for clarification, I'm looking to build on the second part of that loop with other if statements (if it looks weird that I didn't just omit the if (isdigit(motion[i]))
line.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isMotionMeaningful(string motion) //function should return true if it doesn't return false before that
{
for (int i = 0; i != motion.size(); i++)
{
if (!isdigit(motion[i])) //this portion of the loop works in isolation
{
if ((motion[i] != 'W') && (motion[i] != 'w') && (motion[i] != 'S') && (motion[i] != 's') && (motion[i] != 'D') && (motion[i] != 'd') && (motion[i] != 'A') && (motion[i] != 'a') && (motion[i] != '/'))
{
return false;
}
if (isdigit(motion[i]))
{
if ((motion[i] == '0') || (motion[i] == '1')) //if these digits are followed by a number or a slash
{
int j = i + 1;
if (!isdigit(motion[j]) || motion[j] == '/')
{
return false;
}
}
}
}
}
return true;
}
int main ()
{
if (isMotionMeaningful("3w///10d//////////"))
cout << "This case should work\n";
if (!isMotionMeaningful("z3w///10d//////////"))
cout << "This case shouldn't work because it has a bad character\n";
if (!isMotionMeaningful("0w///10d//////////"))
cout << "This case shouldn't work because it uses 0 by itself\n";
if (!isMotionMeaningful("2///10d//////////"))
cout << "This case shouldn't work because it is a number is followed by a slash\n";
return 0;
}
It outputs:
This case should work
This case shouldn't work because it has a bad character
Upvotes: 0
Views: 318
Reputation: 53
I can't comment so I answer it.
There is a reason we use indent carefully, not just for aesthetics. Change the following part:
if (!isdigit(motion[i]))
{
// do something
if (isdigit(motion[i]))
{
// your program will never get here
}
}
to:
if (!isdigit(motion[i]))
{
// do something
} else {
// ...
}
Upvotes: 2