[英]character array validation in C++
我必须使用字符数组验证我的数据“ 123-AB-12345 ”是否正确。 我将字符数组大小设置为 13,包括 '\\0'。 如果条件不满足,该函数必须返回 false。 我所做的就是该程序验证了这 12 个字符,但是当我传递更多值(如“ 123-AB-12345 6789”)时它不会返回错误,并且它返回正确。 我的程序如下:
#include<iostream>
using namespace std;
bool isValidBookId(char bookId[13]);
int main()
{
char book[13];
cin.getline(book,13);
bool id = isValidBookId(book);
cout<<id;
}
bool isValidBookId( char bookId[13] ) {
/* Valid: 098-EN-98712 */
if ( bookId[12] != '\0' )
return false;
if ( bookId[3] != '-' )
return false;
if ( bookId[6] != '-' )
return false;
for ( int i = 0; i < 3; i++ ) {
if ( bookId[i] < '0' || bookId[i] > '9' ) {
return false;
}
}
for ( int i = 4; i < 6; i++ ) {
if ( bookId[i] < 'A' || bookId[i] > 'Z' ) {
return false;
}
}
for ( int i = 7; i < 12 || bookId[12]!='\0'; i++ ) {
if(bookId[13]!='\0'){
return false;
}
if ( bookId[i] < '0' || bookId[i] > '9' ) {
return false;
}
}
return true;
}
我不知道为什么这个条件不起作用。
if ( bookId[12] != '\0' )
return false;
查看您的代码,唯一的解释是数组的最后一个字符为空。 尝试指定这样的分隔符:
cin.getline(book, 13, '\n');
我会参考这个链接:
“如果 n 大于零,则空字符 ('\\0') 会自动附加到写入的序列中,即使提取的是空字符串。”
您的问题在于您的输入功能:
您最多只能阅读 12 个字符。 所以你不能超过 12 个字符。
你可以使用std::string
bool isValidBookId(const std::string&s) {
static const std::regex r{R"(^\d{3}-[A-Z]{2}-\d{5}$)"};
return std::regex_match(std::begin(s), std::end(s), r);
}
int main()
{
std::string s;
while (std::getline(std::cin, s))
{
std::cout << s << ": " << isValidBookId(s) << std::endl;
}
}
或更大的缓冲区:
bool isValidBookId(const char (&s)[14]) {
static const std::regex r{R"(^\d{3}-[A-Z]{2}-\d{5}\0$)"};
return std::regex_match(std::begin(s), std::end(s) - 1, r);
}
int main()
{
char s[14];
while (true)
{
bool b = !!std::cin.getline(s, 14);
if (s[0] == '\0') break;
std::cout << " " << s << ": " << isValidBookId(s) << std::endl;
if (!b) {
std::cin.clear();
std::cin.ignore(255, '\n');
}
}
}
所有条件都正确。 您的问题最初是在输入数据时创建的。
cin.getline(book,13);
'getline' 方法接受任意数量的字符(当然在合理范围内),但只为前 12 个字符分配空间,第 13 个字符将始终只有 '\\0'。 如果你想写更多的字符,让我输入更多的字符。
正确的选项是:
bool isValidBookId(char bookId[100]); // now there is a restriction of not 13 characters, but 100
int main()
{
char book[100]; // now there is a restriction of not 13 characters, but 100
cin.getline(book,100); // now there is a restriction of not 13 characters, but 100
}
bool isValidBookId( char bookId[100] ) // now there is a restriction of not 13 characters, but 100
{...}
如上所述,
cin.getline(book,13) 不会在数组中保存超过 12 个字符。 而是将您的代码替换为:
char book[100]; // To save upto 99 characters
cin.getline(book,100);
并改变
isValidBookId(char bookId[13])
到
isValidBookId( char bookId[100] )
并删除此 isValidBookId 函数中 bookId[12]!='\\0' 的所有检查,因为第 12 个索引处可以有任何字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.