2

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!!

2
  • 1
    Hä?? Don't get your question, what did you try? Commented Dec 25, 2012 at 3:30
  • 1
    That's pretty much the basis. Add the ability to invoke other programs and builtin functions, variable expansion, quoting, and globbing, and you have a shell. Instead parse and interpret some programming language, and you have a REPL (read-execute-print-loop) console. Commented Dec 25, 2012 at 3:30

2 Answers 2

3

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";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.