Thread: User input
View Single Post
Old 04-17-2005, 03:15 PM   #2 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Here it is. Much harder then what you find on the net, but at least it is robust and thourough.
There is a lot left to play with. Have fun.
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib> //size_t
#include <cctype> //isdigit()

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)
{
  bool bNonDigit = false;
  bNonDigit = false;
  
  if(sInLine[0] == '-' || isdigit(sInLine[0]) != 0)
  {
    for(std::size_t 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;
  }  
}
__________________

Last edited by Valmont; 04-17-2005 at 04:56 PM.
Valmont is offline   Reply With Quote