我无法确定我在代码的一部分中做错了什么。我试图做到这一点,以便此循环的第二部分返回false如果有一部分字符串,例如0w
,1w
或5/
。
但是,它会在输入到被调用函数的每个字符串中返回false。
循环的第一部分,我指定只允许某些字符本身,但第二部分不能单独工作。
另外,第一部分在与第二部分组合时不起作用。
我猜,无论我做错什么都是一个非常简单的解决方案,但我不确定它是什么。
另外,为了澄清,我希望用其他if语句构建该循环的第二部分(如果我看起来很奇怪我没有省略if (isdigit(motion[i]))
行。
#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;
}
输出:
This case should work
This case shouldn't work because it has a bad character
答案 0 :(得分:2)
我无法评论,所以我回答。
我们有理由谨慎使用缩进,而不仅仅是美学。 更改以下部分:
if (!isdigit(motion[i]))
{
// do something
if (isdigit(motion[i]))
{
// your program will never get here
}
}
为:
if (!isdigit(motion[i]))
{
// do something
} else {
// ...
}