I am working on using STL and in general safe C++ practices. Instead of posting large samples of code I am working with a small sample to catch problems before I move onto larger ones.
How do you find out if an istringstream
found an input that is not of the desired type? That is, you have a string and you want to verify if it is a float
or not.
Using the program below, when I input
[mehoggan@desktop argument_processing]$ ./args 1 2 3 4 2y
I get:
1 2 3 4 2
which is not what I want, since not all arguments where numeric.
I should of gotten:
ERROR: 2y is not numeric
What improvements would you make to this small program?
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
namespace CLP {
using std::vector;
using std::istringstream;
using std::string;
using std::cerr;
using std::endl;
vector<float> all_numeric_arguments( int argc, char *argv[ ] ) {
vector<float> v_argv;
vector<string> v_tmp;
copy( &argv[1],&argv[argc],back_inserter( v_tmp ) );
for( vector<string>::iterator it=v_tmp.begin( );it!=v_tmp.end( );it++ ) {
istringstream iss( (*it) );
float f=0.0;
if( iss >> f >> std::dec ) {
v_argv.push_back( f );
} else {
cerr << "ERROR: " << (*it) << " is not numeric " << endl;
return v_argv;
}
}
return v_argv;
}
}
int main( int argc, char *argv[ ] ) {
std::vector<float> v = CLP::all_numeric_arguments( argc, argv );
if( v.size( ) == (unsigned)(argc-1) ) {
copy( v.begin( ),v.end( ),std::ostream_iterator<float>( std::cout," " ) );
std::cout << std::endl;
}
}