i am struggling to create a program which takes multiple inputs and determines if they are a string or a number than outputting weather the input is valid or not (input is valid if input argument is a number that may contain decimals). eg. if
"yo man hi 13.9867" is entered program will output
invalid
invalid
invalid
13.9867
(not real code just idea)
if (input is number)
cout the number
else
cout invalid
The base logic is that you do have a word that might be a number. If you can get a number from the word and no characters are left unused, then the whole word is a number.
template <typename T>
bool string_to( const std::string& s, T& result )
{
// Convert string argument to T
std::istringstream ss( s );
ss >> result >> std::ws;
// Stream should be in good standing with nothing left over
return ss.eof();
}
template <typename T>
T string_to( const std::string& s )
{
T result;
if (!string_to( s, result ))
throw std::invalid_argument( "T string_to<T> ()" );
return result;
}
template <typename T>
boost::optional<T> string_to( const std::string& s )
{
T result;
std::istringstream ss( s );
ss >> result >> std::ws;
if (ss.eof()) return result;
return boost::none;
}
You can then attempt to convert an input string to the desired type. If it succeeds then it is valid. If it fails it is not.
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
std::string s;
std::cout << "Enter numbers:\n";
while (getline( std::cin, s ) and !s.empty())
{
double n;
if (string_to<double>( s, n ))
std::cout << "You entered the number " << n << ".\n\n";
else
std::cout << "That was not a number.\n\n";
}
}
or
1 2 3 4 5 6 7 8 9 10 11
int main()
{
std::string s;
std::cout << "Enter numbers:\n";
while (getline( std::cin, s ) and !s.empty())
{
auto n = string_to<double>( s );
if (n) std::cout << "You entered the number " << *n << ".\n\n";
else std::cout << "That was not a number.\n\n";
}
}