Reputation: 3020
I'm writing a c++ program and I want people to be able to operate it from the terminal. The only thing I know how to do is cin
which, though upon receiving the program could act, I wouldn't call a command.
Thanks!!
Upvotes: 2
Views: 3028
Reputation: 11075
In your program, use the alternate int main
signature, which accepts command line arguments.
int main(int argc, char* argv[]);
// argc = number of command line arguments passed in
// argv = array of strings containing the command line arguments
// Note: the executable name is argv[0], and is also "counted" towards the argc count
I also suggest put the location of your executable in the operating system's search path, so that you can call it from anywhere without having to type in the full path. For example, if your executable name is foo
, and located at /home/me
(on Linux), then use the following command (ksh/bash shell):
export PATH=$PATH:/home/me`
On Windows, you need to append your path to the environment variable %PATH%
.
Then call the foo
program from anywhere, with the usual:
foo bar qux
(`bar` and `qux` are the command line arguments for foo)
Upvotes: 0
Reputation: 264649
Try
#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Command: " << argv[0] << "\n";
for(int loop = 1;loop < argc; ++loop)
{
std::cout << "Arg: " << loop << ": " << argv[loop] << "\n";
}
}
Upvotes: 3