...also, a variety of options already exist in the standard library to compare strings.
For messing with command-line arguments, using the
std::
string class is most convenient:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main( int argc, char** argv )
{
vector <string> args( argv + 1, argv + argc );
// Now the args vector contains all the arguments to your program
// (but not the name of the program.)
cout << argv[ 0 ] << " has " << args.size() << " arguments.\n";
for (size_t n = 0; n < args.size(); n++)
cout << n << ": \"" << args[ n ] << "\"\n";
return 0;
}
|
Comparing whether or not something is equal is now just a lookup. There are many ways to do it.
If you just want to know whether a particular argument is listed in
args, and where:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main( int argc, char** argv )
{
vector <string> args( argv + 1, argv + argc );
cout << argv[ 0 ] << " has " << args.size() << " arguments.\n";
for (size_t n = 0; n < args.size(); n++)
cout << n << ": \"" << args[ n ] << "\"\n";
// Find the magic "-hello" argument.
size_t n = std::find( args.begin(), args.end(), "-hello" ) - args.begin();
if (n < args.size())
cout << "Argument number " << n << " told me to tell you \"Hello\".\n";
return 0;
}
|
D:\prog\cc\foo> a
a has 0 arguments.
D:\prog\cc\foo> a one two three
a has 3 arguments.
0: "one"
1: "two"
2: "three"
D:\prog\cc\foo> a x y -hello world
a has 4 arguments.
0: "x"
1: "y"
2: "-hello"
3: "world"
Argument number 2 told me to tell you "Hello".
D:\prog\cc\foo> |
I also have an old post that works very similarly to allow the user to
switch on a string:
http://www.cplusplus.com/forum/beginner/13528/#msg65188
The idea is similar and useful, especially as it examples how to prepare strings for case-insensitive comparison.
If you want to use C-strings, the <cstring> library has the very handy
strcmp() function, which specifically compares strings:
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
If you don't want to #include that, you can use the C++
char_traits<> class to do the same thing:
http://www.cplusplus.com/reference/string/char_traits/
(scroll down to the "compare" and "length" methods).
Hope this helps.