gpt4 book ai didi

c++ - 在 C++ 中为 Date 类重载 >> 运算符会导致无限循环

转载 作者:行者123 更新时间:2023-11-28 03:36:26 24 4
gpt4 key购买 nike

我正在尝试为 C++ 中的 Date 类重载 >> 运算符,但是当运行进入第一个 if 语句时它进入无限循环,你能帮我吗?

//operator
istream& operator >>(istream& is,CustomDate& d){
int day,month,year;
char ch1,ch2;
string test;
is>>skipws>>day>>ch1>>month>>ch2>>year;
if(!is){
is.clear(ios_base::failbit);
return is;
}
if(ch1!='/' || ch2!='/')
error("invalid date input");
d = CustomDate(day,month,year);
return is;
}

这是调用它的函数

CustomDate Menu::inputDate(){
CustomDate date;
cout<<"Input your departure date"<<endl;
cin>>date;
if(!cin){
error("invalid date format");
}
return date;
}

这是调用函数的循环

do{
try{
date = inputDate();
validDate = true;
}
catch(runtime_error& e){
cout<<"Date format not valid! must input as dd/mm/yyyy!"<<endl;
validDate = false;
}
}while(!validDate);

//customdate constructor
CustomDate::CustomDate()
:day(1),month(1),year(2012){}

CustomDate::CustomDate(int day, int month, int year)
:day(day),month(month),year(year){

if(day<0 || day>30)
error("Error: Date constructor");
if(month<0 || month>12)
error("Error: Date constructor");
if(year<0)
error("Error: Date constructor");
}

最佳答案

正如我在评论中所说:

What do you mean by "the clear() function should clear the stream"? It doesn't discard the stream contents, so if there's junk in the stream (such as the character 'a' that can't be parsed as an int) it will never "clear" that junk and will just keep retrying. I think the problem is that clear doesn't do what you think it does.

如果流提取运算符无法提取整数或分隔符错误,则与其从流提取运算符中抛出异常,不如仅从 failbit 中抛出异常(也尝试使用更多的空格来帮助提高代码的可读性):

istream& operator >>(istream& is, CustomDate& d){
int day, month, year;
char ch1, ch2;
if (is >> day >> ch1 >> month >> ch2 >> year)
{
if (ch1 == '/' && ch2 == '/')
d = CustomDate(day, month, year);
else
is.setstate(ios::failbit);
}
return is;
}

然后在 inputDate 中处理失败的提取

CustomDate inputDate(){
CustomDate date;
cout << "Input your departure date" << endl;
if (cin >> date)
return date;

// something went wrong
if (cin.eof())
error("No more data in stream");
else // cin.fail() is true, probably invalid date format
{
// clear error and discard input up to next newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
error("invalid date format");
}
}

关于c++ - 在 C++ 中为 Date 类重载 >> 运算符会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com