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;
}
}