Some Win32 (unmanaged) C++ noob tips

June 22, 2008

This weekend I decided to do a little unmanaged C++.

My biggest take-away was that I learned that unmanaged (aka Win32) C++ is really, really hard and obtuse.  As a C# guy (who used to be a VB6 programmer), I don't think that I appreciated how easy C# and VB6 are to work with.

Here are two things that I tried to do that were hard to figure out: Read a single character from the console and read a line from the console.  Reading a single character is helpful for writing a "press any key to continue..." feature.  Reading a line from the console is helpful for -- well -- reading a line of input from the user.

To read a single character from the console:

  1. Open up your .cpp file

  2. Add the following line somewhere near the top of the file:

    #include "conio.h"

  3. Read the single character with this line:

    int iKeyPress = _getch();

To read a line from the console:

  1. Open up your .cpp file

  2. Add the following lines somewhere near the top of the file:

    #include
    #include

  3. Read the line from the console:

    string message;
    getline(cin, message, 'n');

If you want to get really creative, you can even prompt the user for what you want to do by using "printf" to put a message onto the console.

printf("Type in your name then press ENTER: ");
string message;
getline(cin, message, 'n');

-Ben

Tags: c-sharp