1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/lambda/lambda.hpp>
int main( int argc, char* argv[] ) {
std::vector<int> v; // This is now a vector of ints, nothing else
for( int arg = 1; arg < argc; ++arg ) {
try {
v.push_back( boost::lexical_cast<int>( argv[ arg ] ) );
} catch( const boost::bad_lexical_cast& ) {
std::cout << "argument #" << arg << " is not an integer" << std::endl;
}
}
std::cout << "The ints you specified on the command line were:" << std::endl;
std::for_each( v.begin(), v.end(), std::cout << boost::lambda::_1 << ' ' );
}
| |
So I've used a lot of advanced libraries to make this code as short as possible, and
chances are you aren't familiar with most of them. Anyway, a quick rundown:
boost::lexical_cast<int>() is a function that takes its argument and tries to convert
it to an integer (since I specified int. If I specified double instead, it would have tried
to convert it to a double).
If the conversion fails, boost::lexical_cast<> throws a boost::bad_lexical_cast
exception. The last line -- std::for_each -- is an advanced way to print out the
contents of the vector in a single line of code.
But see how with templates, I essentially had to decide at compile time that the program
would only recognize ints and store them.