【发布时间】:2019-09-11 07:26:18
【问题描述】:
这应该检查输入的字符串是否是有效的许可证号。有效数字不能包含任何小写字母或空格。如果我输入“cat”,它应该看到字符“c”较低,因此应该将 bool isValid 设置为 false,从循环中中断,然后打印“cat is not a valid license number”。然而它没有,它只是使 bool isValid 成为我一开始设置的任何东西,这是真的。因此,如果我将其初始化为 false 并输入“CAT”,isValid 仍然是 false。
int main()
{
// Input
cout << "Enter a valid license number: ";
string license_number;
getline(cin, license_number);
cout << endl;
// Initialize boolean
bool isValid = true;
// Loop to check for space or lowercase
for (int i = 0; i < license_number.size(); i++)
{
if (isspace(license_number[i]) || islower(license_number[i]))
{
bool isValid = false;
break;
}
else
bool isValid = true;
}
// Output
if (isValid == true)
cout << license_number << " is a valid license number." << endl;
else
cout << license_number << " is not a valid license number." << endl;
return 0;
}
【问题讨论】:
标签: c++