Extracting ints and chars together

  • Thread starter Thread starter auk411
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
auk411
Messages
54
Reaction score
0

Homework Statement



I need to know how, in C++, to extract 3 integers and 2 chars. In other words, I need to extract from the keyboard this data: HH:MM:SS, where the HH, MM, and SS are integers (standing for hours, minutes, and seconds). The two semicolons are chars. There are NO spaces, returns, other whitespaces. So when the user enters the appropriate numbers into HH:MM:SS how do I extract the information keeping the hours as the hours, the chars as the chars, minutes as the minutes, and seconds as the seconds.

Homework Equations



cin can't be the answer because it delimits using whitespace, and there is no whitespace. I also haven't been taught how to convert strings to ints. So I doubt that is the way the prof
wants us to go.

The Attempt at a Solution


 
Physics news on Phys.org
Here's the C style of doing this.
Code:
#include <stdio.h>
.
.
.
int hrs, mins, secs;
printf("Enter the time as HH:MM:SS.\n");
scanf(" %d:%d:%d", &hrs, &mins, &secs);
.
.
.

BTW, ':' is a colon. A semicolon is this character - ';'
 
The scanf-solution is my preferred solution, although I'd check if the return-value of scanf() equals 3 (the number of fields succesfully parsed).

Here's an alternate, more C++ like, solution:

Code:
int hrs, mins, secs;
char ch;
std::cout << "Enter the time as HH:MM:SS." << std::endl;
if (std::cin >> hrs >> ch >> mins >> ch >> secs)
{
   ...
}

This one is less neat, because it depends on the format of the input string to be correct.

[EDIT]Note that the more C++ like way of doing things is in this case is worse the the old way to do it!
Also note that the old C style way still works in C++![/EDIT]
 
Here's a fancy way of doing it by overloading the >> operator. All in all, a fairly elegant solution, IMO. The ignore method comes in handy. You can also overload the << operator to print it out, of course.

Code:
#include <iostream>
#include <iomanip>

class Time
{
public:
    int hours, minutes, seconds;
    friend std::istream &operator >> (std::istream &is, Time &t);
};

std::istream &operator >> (std::istream &is, Time &t)
{
        is >> t.hours;
        is.ignore(1,':');
        is >> t.minutes;
        is.ignore(1,':');
        is >> t.seconds;
        return is;
}

int main(int argc, char *argv[])
{
    Time t;
    std::cin >> t;

    std::cout << std::setw(2) << std::setfill('0') << t.hours << ":"
              << std::setw(2) << std::setfill('0') << t.minutes << ":"
              << std::setw(2) << std::setfill('0') << t.seconds << '\n';

    return 0;
}
 
Last edited: