【发布时间】:2020-01-02 18:23:33
【问题描述】:
我正在创建一个 c++ 程序来使用 c++ 中的函数验证书籍 ID。如果输入有效,程序必须返回 1,如果输入无效,程序必须返回 0。输入模式:“123-AB-12345”这将被视为有效输入。有效输入是: (a) 字符总数必须为 12 (b) 前三个字符必须是 1 到 9 的整数。 (c) 第 4 和第 7 个字符必须是后缀“-”。 (d) 最后 5 个字符必须是 1 到 9 的整数。
我尝试了以下方法,但没有得到想要的答案。需要帮助吗
#include<iostream>
using namespace std;
bool isValidBookId(char bookId[13]);
int main()
{
char book[13];
cin.getline(book,12);
bool id = isValidBookId(book);
cout<<id;
}
bool isValidBookId(char bookId[13])
{
int i;
bool check1,check2,check3,check4,check5,check6;
check1=check2=check3=check4=check5=true;
if(bookId[12]=='\0'){
check1=true;
}
if(bookId[3]=='-')
{
check2=true;
}
if(bookId[6]=='-')
{
check3=true;
}
for(i=0; i<3;i++){
if(bookId[i]>=0 || bookId[i]<=9)
{
check4=true;
}
}
if(bookId[i]>= 'A' || bookId[i]<= 'Z')
{
check5=true;
}
for(i=7; i<12; i++)
{
if(bookId[i]>=0 || bookId[i]<=9)
{
check6=true;
}
}
if(check1==true && check2==true && check3==true && check4==true && check5==true && check6==true)
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
您是否使用过调试器来查看哪个检查失败?你为什么要检查
bookId[12] == '\0'inside 你的 for 循环?答案不会改变。此外,您将所有检查初始化为true,并且从不将任何检查设置为false。 -
哦,我刚刚删除了那个 for 循环,但我什至没有得到它。结果始终为 1。@ChrisMM 此外,我使用 bookId[12]=='\0' 在 char 数组(bookId[ ])的末尾标记一个空字符,以便用户只能输入 12 个字符(索引 0 到 11并且在索引 12 它显然是 '\0' (空字符)
-
你永远不会初始化
check6。如果您使用其未初始化和不确定的值,那么您有 未定义的行为。 -
另外注意,如果你有
if (some_condition) return true; else return false;,那正好等于return some_condition;。
标签: c++ validation user-input