user1888527
user1888527

Reputation: 565

C++ - Overloading operator>> and processing input using C-style strings

I'm working on an assignment where we have to create a "MyInt" class that can handle larger numbers than regular ints. We only have to handle non-negative numbers. I need to overload the >> operator for this class, but I'm struggling to do that.

I'm not allowed to #include <string>.

Is there a way to:

a. Accept input as a C-style string
b. Parse through it and check for white space and non-numbers (i.e. if the prompt is cin >> x >> y >> ch, and the user enters 1000 934H, to accept that input as two MyInts and then a char).

I'm assuming it has something to do with peek() and get(), but I'm having trouble figuring out where they come in.

I'd rather not know exactly how to do it! Just point me in the right direction.

Here's my constructor, so you can get an idea for what the class is (I also have a conversion constructor for const char *.

MyInt::MyInt (int n)
{
   maxsize = 1;

   for (int i = n; i > 9; i /= 10) {
      // Divides the number by 10 to find the number of times it is divisible; that is the length
      maxsize++;
   }

   intstring = new int[maxsize];

   for (int j = (maxsize - 1); j >= 0; j--) {
      // Copies the integer into an integer array by use of the modulus operator
       intstring[j] = n % 10;
       n = n / 10;
   }
}

Thanks! Sorry if this question is vague, I'm still new to this. Let me know if I can provide any more info to make the question clearer.

Upvotes: 0

Views: 321

Answers (1)

So what you basically want is to parse a const char* to retrieve a integer number inside it, and ignore all whitespace(+others?) characters.

Remember that characters like '1' or 'M' or even ' ' are just integers, mapped to the ASCII table. So you can easily convert a character from its notation human-readable ('a') to its value in memory. There are plenty of sources on ascii table and chars in C/C++ so i'll let you find it, but you should get the idea. In C/C++, characters are numbers (of type char).

With this, you then know you can perform operations on them, like addition, or comparison.

Last thing when dealing with C-strings : they are null-terminated, meaning that the character '\0' is placed right after their last used character.

Upvotes: 2

Related Questions