Reputation: 31
So this was my original code:
#include <iostream>
using namespace std;
int main ()
{
float x;
cout << "Please enter an integer value: ";
cin >> x;
if ((x >= 100) && (x < 200)) {
cout << "split";
} else if (x == 0 ||x == 1 ) {
cout << "steal";
} else {
cout << "split";
}
system("pause");
}
It works perfectly, but I need it to run this way:
C:\> program.exe 109
it will read 109
and give the output - "steal"
.
C:\> program.exe 0.5
it will read 0.5
and give me the output "split"
.
What do I have to add to my original code to do this?
Upvotes: 3
Views: 1033
Reputation: 1197
Can we have more clarity on the question? Do you want to know how to execute the code using command line arguments? In that case here it is:
int main (int no_of_args, char* arglist[])
{
}
In argList
, the first item holds the name of the executable and subsequent items hold the inputs provided.
Upvotes: 0
Reputation: 2261
you can do this by using command line arguments. Here is format for main function:
int main (int argc, _TCHAR* argv[])
{
}
Here argc
represents number of arguments(returns 2 in your case, program.exe 0.5 )
argv
represents two strings. 1st containing program.exe
and second containing 0.5
.
This way you can solve you problem
Upvotes: 0
Reputation: 1698
Change your main to
int main (int argc, char** argv)
The you can check number of specified parameters to your program in argc
and the values (as char *
) in argv
. You can convert that values to float using std::stof
float x = 0.0f;
if (argc > 1) {
x = std::stof(argv[1]);
} else {
std::cerr << "Not enough arguments\n";
return 1;
}
Please note that the first argument to the program is the name of the executable itself (program.exe
in your case), so you need to check for at least two arguments.
References: http://en.cppreference.com/w/cpp/string/basic_string/stof
Upvotes: 5