Thread: User input
View Single Post
Old 04-19-2005, 05:44 PM   #4 (permalink)
Feis
Registered User
 
Join Date: Apr 2005
Posts: 18
Feis is on a distinguished road
Well, here is an (ever so slightly) modified version. After first running some tests, I realized if you typed a space first, you tricked the entire if statement, as it was only looking for "-" or whether it was a digit. To fix this, I added another clause to the if statement, (isspace() from cctype). I also took cstdlib, and took out size_t for an int. Althoguh I got a warning from the compiler, no errors arised, although I am sure there was a reason for the size_t declaration.

If I may ask, what is a size_t variable? I cant seem to find a definition with google, or some other code sites.

As a final piece, I tried to remove the need for the sstream lib, using indirection to get the contents of the string into an int variable, but it didnt work.
Code:
#include<iostream>
#include <string>
#include <sstream>
#include <cctype> //isdigit() and isspace()

using namespace std;

//C++ allows conversion from a floating point to integer. But this function
//doesn't allow that. It wants "strict" (signed) integers only. 
bool string_to_strict_int(const string& sInLine, int& dest);

int main()
{
  string sNumInput;
  int myInt;
  
  //As long as the user doesn't enter a valid, strict (non-floating point)
  //(signed) integer, we keep on asking for one.
  while(string_to_strict_int(sNumInput, myInt) == false )
  {
    cout<<"Please enter an integer"<<endl;
    cout<<"-> : ";
    getline(cin, sNumInput);
  }
  
  //And here we have our (signed) integer at our disposal.
  cout<<myInt<<endl;
  
  cin.get();
  return 0;
}

bool string_to_strict_int(const string& sInLine, int& dest)
{  
  if(sInLine[0] == '-' || isdigit(sInLine[0]) != 0 || isspace(sInLine[0]))
  {
    for(int i = 1 ; i < sInLine.size(); ++i )
    {
      if( !isdigit(sInLine[i] ))
      {
        return false;
      }
    }      
  }
  
  istringstream  InStream( sInLine );
  InStream >> dest;
  if( !InStream )
  {
    //Oops, empty string found. That's not an integer either.
    return false;
  }
  else
  {
    //All went successfull. We had a strict integer value passed to this funct.
    return true;
  }  
}
Feis is offline   Reply With Quote