0

I know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.

#include <iostream>
#include "getopt_pp_standalone.h"

using namespace GetOpt;
using namespace std;

 int main(int argc, char* argv[])
 {
    string who;

    GetOpt_pp ops(argc, argv);

    ops >> Option('n', "name", who, "world" );              /* the default name is 'world' */

    cout << "Hello " << who << "!" << endl;

    return 0;
}
Clark
  • 31
  • 6

1 Answers1

0

Variants of getopt get options from the command line rather than input by a user.

You will need to run your program with something like:

myprog -n Pax

If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:

std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";

A few other things to impart:

First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.

Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:

std::cout << "blah, blah, blah\n";

Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • How can I do it outside of the command line or in the program itself? – Clark Feb 25 '13 at 09:09
  • @Kay, have updated answer with a suggestion on how to do that. Keep in mind it's just one way and it's simple so doesn't allow a default value. You can expand on the code to add that if necessary. – paxdiablo Feb 25 '13 at 09:15