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.