lights,
Added whitespace trimming to front and back of input.
De-templatized 'getValue' which now expects 'value' refernece to be of type float.
Added whitespace trimming to front and back of input.
De-templatized 'getValue' which now expects 'value' refernece to be of type float.
Code:
#include <iostream>
#include <string>
#include <sstream>
#if 0
void getInput(float& value, const std::string& strPrompt, const std::string& strRepromptError)
{
do
{
std::cout << strPrompt << std::flush;
std::string str;
getline(std::cin, str);
std::istringstream iss(str);
if ( iss >> value )
{
break;
}
std::cout << strRepromptError << std::endl;
} while ( true );
}
#else
void getInput(float& value, const std::string& strPrompt, const std::string& strRepromptError)
{
std::string strTrimChars(" \t\r\n");
int decimal_points;
bool invalid;
std::string str;
do {
std::cout << strPrompt << std::flush;
getline(std::cin, str);
if ( std::string::npos != str.find_last_not_of(strTrimChars) )
{
str.erase(str.find_last_not_of(strTrimChars) + 1) ;
}
str.erase(0, str.find_first_not_of(strTrimChars)) ;
invalid = false;
decimal_points = 0;
std::string::iterator itr = str.begin();
if ( ('-' == *itr) || ('+' == *itr) )
{
itr++;
}
for ( ; itr != str.end(); itr++ )
{
if ( !isdigit(*itr) )
{
if ( ('.' == *itr) && (++decimal_points <= 1) )
{
continue;
}
invalid = true;
std::cout << strRepromptError << std::flush;
break;
}
}
} while ( invalid );
std::istringstream iss(str);
iss >> value;
}
#endif
int main(int argc, const char* argv[])
{
std::string strError("Invalid entry, please try again!\n");
float value;
while ( true )
{
getInput(value, "Give me a number: ", strError);
if ( value >= 0.0f )
{
break;
}
std::cout << "Sorry, please provide a positive value!\n\n";
}
std::cout << "User provided value: " << value << std::endl;
return EXIT_SUCCESS;
}