C++ 如何验证字符串中的最后四个字符是否在1900和2000之间?
如何验证字符串中的最后四位数字是否在1900和2100之间(包括1900和2100)?我甚至不需要确切的答案,但至少需要如何检查字符串中的数字C++ 如何验证字符串中的最后四个字符是否在1900和2000之间?,c++,C++,如何验证字符串中的最后四位数字是否在1900和2100之间(包括1900和2100)?我甚至不需要确切的答案,但至少需要如何检查字符串中的数字 string getDate() { string date = ""; cout << "\nEnter a date in military format (DDMMMYYYY) such as:\n" << "-- 13MAR1999 for March 13, 1999\n"
string getDate()
{
string date = "";
cout << "\nEnter a date in military format (DDMMMYYYY) such as:\n"
<< "-- 13MAR1999 for March 13, 1999\n"
<< "-- 01APR2025 for April 1, 2025\n"
<< "-- Note: year must be between 1900-2100.\n"
<< "Entry --> ";
cin >> date;
while(date.length() > 9 || date.length() < 9)
{
cout << "\nInvalid entry, must be 9 characters.\n";
getDate();
}
if (date[5] < 1 || date[5] > 2)
{
cout << "\nYear must be between 1900-2100.\n";
getDate();
}
return date;
}
string getDate()
{
字符串日期=”;
CUT目前,您的检查“<代码> >(日期[5 ]<1)日期[5 ]>2)/代码>并不是您所希望的。大多数C++(和C)编译器都会在ASCII之后编码其字符。因此字符<代码> '0' < /COD>(通常)具有整数值<代码> 48 < /COD>,字符<代码> '1' < /代码>(通常)具有整数值
49
,依此类推
当前代码的另一个问题是递归。下面的代码将无限期地循环、打印输出和递归。(即使下一个日期条目有效,它也将继续循环。)
数字1和字符“1”之间有很大很大的区别。我重复了一遍,它们不一样。你可以从修复代码中的这个错误开始,这样它就可以正确地检查1000-2999的范围,然后一旦你弄明白了,弄明白如何调整1000-2100的检查应该很容易。试试单引号aro你的“1”和“2”@SamVarshavchik我不会说它很大。'1
和1
之间的区别是48:)(ascii编码)您可以使用输入的字符串数据来进行划时代的表示,如在这个帖子中。在1900和2100年间进行EPOCH时间表示,然后使用比较操作符在这里做递归调用,这样C++就不能保证使用ASCII,即使这是最常见的情况。虽然没有使用SCII,但我对我的语言进行了限制。some.Nit.会建议if(noIntTrack!=4){…}否则如果(1990@DavidC.Rankin)我已将解决方案更改为使用返回值
。不过感谢您的建议。:-)
while(date.length() > 9 || date.length() < 9)
{
cout << "\nInvalid entry, must be 9 characters.\n";
getDate();
}
string getDate()
{
std::string date = "01APR2021"; // read date (or hard-code it)
// perform checks
if (date.length() != 9) // you can simplify your length check
{
// error message
return getDate(); // beware of your while-loop and recursion
}
std::string lastFour(date.end() - 4, date.end()); // substring of last four characters of date
std::string::size_type noIntTrack; // tracks the stoi finishing position
int year = std::stoi(lastFour, &noIntTrack); // converts the year to an integer
if (noIntTrack != 4) // if not 4 => unsuccessful conversion
{ // e.g. maybe user entered 01APR20AA
// error handling:
// noIntTrack should be 4 to signify successful conversion of all characters
return getDate(); // recurse
}
if (!(1990 <= year && year <= 2100)) // check if year not in range
{
// handle year out of range
return getDate();
}
// other checks (e.g. month/date?)
// if (date is not good) { return getDate(); }
// date is valid:
// party
return date;
}