我想要做的是按照这种格式输入一个日期,Wednesday 7:05 PM
然后将其分成令牌以放入我拥有的结构中。我的主要问题是我正在使用的 stringstream 对象没有从输入缓冲区中删除已经输入的字符串,所以在我第二次检查几个小时它失败了,因为它输入了 char 类型的东西到无符号中。我该如何解决?另外,如果您对我清理代码有任何建议,我将不胜感激。
struct Time{
// always in [0, 6]:
// 0 means Sunday, 1 means Monday, ... , 6 means Saturday
unsigned day;
// false means at or after midnight, and before the following noon (AM)
// true means at or after noon, and before the following midnight (PM)
bool pm;
unsigned hour; // in [1, 12], e.g. 12 for 12 o’clock
unsigned minute; // in [0, 59]
}; // struct Time
const string dayar[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void input( Time & time ){
string str, day, pm;
unsigned hr, min;
getline(cin,str);
istringstream sin(str);
cout<<str.length();
for(unsigned i=0; i<str.length(); i++){
if(str[i]==':')
str[i]=' ';
}
if(!(sin>>day)){
die("AHHHHH!!! WHERE'S THE INPUT?!?!?!");
}else{
for(unsigned i=0; i<7; i++){
if(day==dayar[i]){
time.day=i;
}
}
}
if(!(sin>>hr)){
die("AHHHHH!!! WHERE'S THE INPUT?!?!?!");
}else{
if(hr<1 || hr>12){
die("THAT NUMBER AIN'T A REAL HOUR!!");
}else{
time.hour=hr;
}
}
if(!(sin>>min)){
die("AHHHHH!!! WHERE'S THE INPUT?!?!?!");
}else{
if(min<0 || min>59){
die("THAT NUMBER AIN'T A REAL HOUR!!");
}else{
time.minute=min;
}
}
if(!(sin>>pm)){
die("AHHHHH!!! WHERE'S THE INPUT?!?!?!");
}else{
if(pm!="PM" || pm!="AM"){
die("THAT NUMBER AIN'T A REAL HOUR!!");
}else{
pm=="PM"?time.pm=true:time.pm=false;
}
}
}
bool die(const char *msg){
cout<<msg;
exit(EXIT_FAILURE);
}