I created a guessing game program, and now I have to add a command line argument to it - in this case, if the user runs the program and adds "-n 150" to the end the program will randomly pick a number between 150 and 1 as opposed to the default 100.
#include <iostream>
#include <string.h>
#include <cstdlib>
usingnamespace std;
;
int main(int argc, char *argv[])
{
cout << argv[1] <<endl;
if (argv[1] == "-n")
{
//convert string into integer
int i;
sscanf (argv[2], "%d", &i);
srand (time(NULL));
int x, y = rand() % i;
cout << "I'm thinking of a number between 0 and 100. Can you guess it?" << endl;
do
{
cin >> x;
if (x > y)
cout << "I'm thinking of a smaller number. Please try again." << endl;
elseif (x < y)
cout << "I'm thinking of a larger number. Please try again." << endl;
}
while (x != y);
cout << "Correct! You guessed the secret number!" << endl;
return 0;
}
else;
int i;
srand (time(NULL));
int x, y = rand() % 101;
cout << "I'm thinking of a number between 0 and 100. Can you guess it?" << endl;
do
{
cin >> x;
if (x > y)
cout << "I'm thinking of a smaller number. Please try again." << endl;
elseif (x < y)
cout << "I'm thinking of a larger number. Please try again." << endl;
}
while (x != y);
cout << "Correct! You guessed the secret number!" << endl;
return 0;
}
The problem, unfortunately, is that I'm not getting anywhere with this command line argument: am I doing something wrong with if (argv[1] == "-n")?
Er, that won't work, and it tests on the wrong thing. [edit] Hey, that's not what I saw a moment ago (am I seeing things?) ... but it still tests on the wrong thing.
Just convert to std::string to do comparisons:
1 2
#include <iostream>
#include <string>
1 2 3 4 5
if ((argc > 2) // because it is PROGNAME "-n" NUMBER
&& (string( argv[ 1 ] ) == "-n"))
{
//stuff goes here
}
BTW, you can avoid a lot of code duplication by just getting the number before the game starts.