gotoxy() function in Visual C++?

1 03 2009


I often feel nostalgic about the gotoxy() function in old Turbo C++. The gotoxy() is used to “jump” to any point of the console screen. I used that function to create nice menu effects. But unfortunately in visual C++, gotoxy() is not available. But is there any other api which can be used instead of gotoxy()?

gotoxy1


You can use SetConsoleCursorPosition(). Check out the following sample program. It reads an integer in loop and prints the time in the right hand corner of console. Just a demonstration of Visual C++’s gotoxy().

gotoxy2

#include "iostream"
#include "time.h"
#include "windows.h"

using namespace std;

// Set current cursor position.
void GotoXY( HANDLE StdOut, SHORT x, SHORT y )
{
    // Set the cursor position.
    COORD Cord;
    Cord.X = x;
    Cord.Y = y;
    SetConsoleCursorPosition( StdOut, Cord );
}

// Print time at the upper right corner of console.
void PrintTime()
{
    // Get handle to console output buffer.
    HANDLE hStdout = GetStdHandle( STD_OUTPUT_HANDLE );  

    // Get current screen information.
    CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo = { 0 };
    GetConsoleScreenBufferInfo( hStdout, &ScreenBufferInfo ); 

    // Set the cursor position to upper-right of console.
    GotoXY( hStdout, 50, 0 );

    // Get time and display it.
    time_t tim=time(NULL);
    char *s=ctime(&tim);
    cout << s; 

    // Reset cursor back to position.
    GotoXY( hStdout,
            ScreenBufferInfo.dwCursorPosition.X,
            ScreenBufferInfo.dwCursorPosition.Y );
} 

void main(int argc, char* argv[])
{
    // Just to provide enough space.
    cout << endl << endl; 

    while( true )
    {
        // Print the time.
        PrintTime(); 

        // Read a value.
        int a;
        cout << "Enter number: ";
        cin >> a;
    }
}


Yes! After a short break, I’m back. 🙂 You’ll soon have a happy news from me, within a week. 😉 Keep watching.


Targeted Audience – Beginners.

Advertisements