What I’m trying to do is input a date following this format Wednesday 7:05 PM Then separate it into tokens to put in a struct i have. My main problem is the stringstream object i am using doesn’t remove the already inputted string from the input buffer so on my second check for hours it fails because its inputting something of type char into an unsigned. How do i fix this? Also if you have any advice on me cleaning up the code i’d appreciate it.
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);
}
I don’t see why you wouldn’t read the values in one statement. Something like this:
I mean, if you wanna squawk about every conceivable date parsing error then go ahead! =) But it just makes for cluttered code that’s hard to follow.