Thread: User input
View Single Post
Old 04-21-2005, 06:50 PM   #6 (permalink)
Feis
Registered User
 
Join Date: Apr 2005
Posts: 18
Feis is on a distinguished road
Ok, after perhaps more careful reflection the function, I think I found a way to simplify the catching of bad input. Basically what this does is that it will _only_ accept input that beigns with "-" or a digit. Otherwise, it reverts to the else statement I wrote in, which returns false. not only is this simpler I think but more foolproof and easier to understand. In retrospect, I dont see why it should have accepted the first character as a space. I'm working on learning sstream, but the midtrimester crush is on Heres the relevant part of the code:


Code:
bool string_to_strict_int(const string& sInLine, int& dest)
{  
  if(sInLine[0] == '-' || isdigit(sInLine[0]) != 0)
  {
    for(size_t i = 1 ; i < sInLine.size(); ++i )
    {
      if( !isdigit(sInLine[i] ))
      {
        return false;
      }
    }
  
  }
  else 
  {return false;}
EDIT: after briefly looking @ istringstream, and a quick test, I found that I could remove the test to see whether the string was null:
Code:
if( !InStream )
  {
    //Oops, empty string found. That's not an integer either.
    return false;
  }
as if the first character was null or a break, the function already returned a false value for it, and there would be no need to check again to see whether it was empty. I remember reading that its always a good idea to check that your stream has data in it(I've dabbled in file input), but I would think that this test has already been performed and therefore the only purpose that code snippet would serve is to make it clear that the stream is being tested. So I ask, what should be done in a situation like this?

Remove redundancy, or make the code more reader friendly?

You could also comment in that the check is already being performed, but a lot is going on in that nest of if and for statements, so I dont think the comments would be effective enough.

Last edited by Feis; 04-21-2005 at 07:33 PM.
Feis is offline   Reply With Quote