throw instance error

Hey everyone,
So the user input is in the form of "##:##:##"
Variables: Hour Minute and Second respectively.
I create a string and split it. The parts are stored in a Time class object.
I have the >> operator overloaded:
// NOTE >> used several places not listed here for class input.

The problem I'm having is:
1
2
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr

The code below is the two functions involved.

1
2
3
4
5
6
7
istream& operator >> (istream &in, Time &time1)
{
   string input;
   in >> input;
   time1.hour = atoi(input.substr(0,2).c_str());
   time1.minute = atoi(input.substr(3,2).c_str());
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Time::promptForTime(string prompt, bool readSeconds)
{
   string input;
   cout << prompt;
   // If no seconds skip input seconds
   if (readSeconds = false)
      cin >> *this;
   else
     {
   //********NOTE cerr reaches here
      cin >> input;
      this->hour = atoi(input.substr(0,2).c_str());
      this->minute = atoi(input.substr(3,2).c_str());
      this->second = atoi(input.substr(6,2).c_str());
    //*******NOTE cerr doesn't reach here
     }
}

Any help would be appreciated. Thank You
-Edithsong
Last edited on
You do realize that this:

if (readSeconds = false)

should have a double equals sign. With the code as is, the else statement is always executed. The substr call throws a std::out_of_range exception if the position where you want to start the substring is beyond the range of the string. Maybe it's going down into your else statement (with the user not inputting the seconds) and then this call:

this->second = atoi(input.substr(6,2).c_str());

is going out of range of your string.
Thank you I spent a solid hour trying to solve that. Your awesome!
Topic archived. No new replies allowed.