views:

179

answers:

3

How do I read in a variable number of characters? The user can input a positive or negative number that is too big to be stored in an integer. I am then checking to make sure the char is a number and storing it in an array of ints (although that will probably be changed to a short since I only need to be able to store 0-9).

istream& operator>>(istream &in, LargeInt &l)
{
  char x;
  do
  {
      cin >> x;
      int v = (int)x;

      switch( v )
      {
          case 48: v = 0;
          case 49: v = 1;
          case 50: v = 2;
          case 51: v = 3;
          case 52: v = 4;
          case 53: v = 5;
          case 54: v = 6;
          case 55: v = 7;
          case 56: v = 8;
          case 57: v = 9;
          default: v=10 /* END INPUT */;
      }

      l.largeInt[ l.usedLength ] = v;
      l.usedLength++;
      //need to check array length and make bigger if needed
  }
  while( (x == 45) || ((x > 47) && (x < 57)) );
}
+2  A: 

Why not input a string, and then convert it to a number?

Vlad
+3  A: 

A few points. First of all, if you only need to store values from 0 to 9, you might as well store them in a char (which is just a small integer type in C++).

Second, you probably need to add a break; to the end of all the cases in your switch statement -- in C++, execution falls through from one case to the next without a break to stop it. Then again, you should probably just get rid of the switch statement entirely. You'd probably be better off using isdigit from <ctype.h>. Since char is a small integer type in C++, you can also do math on it, so you could just subtract '0' from each digit after verifying that it is a digit. Edit: contrary to the later edit, I would strongly advise against subtracting 48 from each digit. First of all, it's not guaranteed to work (and won't with some character sets -- even if you don't think your code will ever be used on an IBM mainframe, it's a poor habit). Second, it makes the intent much more apparent. I don't think there's a good reason to expect the reader to have memorized the ASCII table so they'll know that 48 is equivalent to '0'.

Finally, to deal with the problem you knew you had, you'll probably want to look up std::vector.

Jerry Coffin
+2  A: 

If you wish to read digits, you need to do it a character at a time. E.g.

char ch;
while (std::cin.get(ch) && ch >= '0' && ch <= '9') {
    // You have a digit to process (maybe you want to push_back it into a vector)
}

Notice that you need to use ch - '0' to get the value of the digit because ch contains the character code rather than the value. In ASCII this means that '0' is in fact 48, '1' is 49 and so on (and 'A' is 65). The values may be different for different character encodings but the digits are guaranteed by the standard to be sequential, so that subtracting zero works.

Tronic