0

I want to override my extraction operator for MyClass, which has three int attributes, the first one has no more than three digits, the second one two and the last one.

The input has to be strictly like this: 123-45-6789, if one of the parts has less digits than the maximum, the user must enter extra 0s, like 001-02-3456.

How should I make this? Should I read each letter as a char and then create the three ints? What would be the best way to create an int given a number of chars?

dabadaba
  • 9,064
  • 21
  • 85
  • 155
  • This is a bit broad, you essentially have to take a string as input and then validate it, you'd have to ensure that there were valid characters, 2 `-` separators, then attempt to convert the characters to an int and then pad with leading zeroes – EdChum Apr 12 '14 at 11:03
  • I would use [Boost.Spirit](http://www.boost.org/doc/libs/1_55_0/libs/spirit/doc/html/index.html) but it's certainly an overkill :) – user3159253 Apr 12 '14 at 11:05
  • Just learn how to pad [leading zeroes](http://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator) and [overload << operator](http://stackoverflow.com/questions/10291385/overloading-operator-for-stdostream). – Mohit Jain Apr 12 '14 at 11:05
  • I think I wasn't clear about the zeroes. The user has to enter leading zeroes but then each part of the input "code" goes to an int. – dabadaba Apr 12 '14 at 11:06

1 Answers1

0

You can do it like that:

MyClass{
    int a,b,c;
    MyClass(const char * str)
    {
        a = b = c = 0; 
        while(*str!='-')
        {
            if(*str<'0' or *str>'9')
            {
                throw std::std::invalid_argument("");
            }
            else
            {
                a=a*10+(*str)-'0';
                ++str;
            }
        }
        while(*str!='-')
        {
            if(*str<'0' or *str>'9')
            {
                throw std::std::invalid_argument("");
            }
            else
            {
                b=b*10+(*str)-'0';
                ++str;
            }
        }
        while(*str!=0)
        {
            if(*str<'0' or *str>'9')
            {
                throw std::std::invalid_argument("");
            }
            else
            {
                c=c*10+(*str)-'0';
                ++str;
            }
        }
    }
};

or even simpler....