Here is the code in question: it can read from the console and parse the string, but I want it to parse the string with initial numeric value doubled. For example....
An appropriate library would make this particular task nicer. Boost.Range or Eric Niebler's library ( https://github.com/ericniebler/range-v3 ) could help, for example.
Put s = filter( s );
between lines 18 and 19 of your code, with filter() as below.
1 2 3 4 5 6 7 8 9 10 11 12 13
std::string filter( std::string s )
{
try
{
int d = std::stoi( s ); // use for ints only
// double d = std::stod( s ); // use for doubles, but little control over formatting
return std::to_string( 2 * d );
}
catch( ... )
{
return s;
}
}
1. Using std::regex to handle negative and decimal numbers
2. cut down a line of code by initializing the std::vector<std::string> directly with the std::istringstream object's initialization:
Avoid using a custom regular expression to parse floating point numbers. There are too many edge cases to handle; a correctly written regular expression would be horrendously complex.
For instance all these are all valid representations of numbers: 1.23e-99, inf, 0xab.cdP-23
On most implementations, this is not (it is out the range of values that can be represented): 1.0e56789
Let either a string stream or std::stold do the heavy lifting; in both cases incorporate checks for failure.
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// if the string contains the representation of a number
// place the value of the number in var and return true
bool parse_number( const std::string& str, longdouble& var )
{
try
{
// http://en.cppreference.com/w/cpp/string/basic_string/stof
std::size_t parsed_till ;
constauto num = std::stold( str, std::addressof(parsed_till) ) ;
if( parsed_till == str.size() ) // if fully parsed
{
var = num ;
returntrue ;
}
}
catch( const std::exception& ) {}
// if we get here, either str does not contain the representation of a number
// or the value it represents is out side the range of numbers that we can handle
var = 0 ;
returnfalse ;
}
int main()
{
std::string str;
std::getline( std::cin, str );
std::cout << "You entered: " << std::quoted(str) << '\n' ;
std::istringstream stm(str);
std::string token ;
while( stm >> token )
{
longdouble number ;
if( parse_number( token, number ) ) std::cout << number*2 << '\n' ;
else std::cout << std::quoted(token) << '\n' ;
}
}