Hi all,

I want to take the position of cursor from the command line and also want it to go to specific location. But I dont know how to accomplish that.

I have tried with cout.seekp () and cout.tellp (). But they didnt worked as I hoped. seekp () and tellp () did work with files. These are not working with command line and cout.tellp () is returning -1 showing that tellp () has failed. cout.seekp () is printing on the command line where the cursor, not taking it to the value I passed to seekp as argument.

The following code is the one I tried.

//17-july-09		14.02

#include <iostream>

using namespace std;

int main ()
{
	int pos = 0;

	cout << "Hello World!";

	pos = cout.tellp ();	//to get the position of cursor

	cout << pos << endl;	//this displays -1

	cout.seekp (400);	//want to take cursor to some other location (like 400)

	cout << "$" << endl;	//and print $ at that position
			//but the cursor remains where it is and prints $ there, not at the specified location
	return 0;
}

Any help would be appreciated.

I am using Windows Vista and MS Visual C++.

thx. Got the cursor to required destination. But how to know where is it now??? I have to decide where to take it after knowing where it is at present.

for windows console programs:

include the header file <windows.h>

//get the current position of cursor
COORD screen::getpos()
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;
	COORD coord;

    if(GetConsoleScreenBufferInfo (
        GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
    {
        coord.X = csbi.dwCursorPosition.X;
        coord.Y = csbi.dwCursorPosition.Y;
        return coord;
    }
    else
    {
        coord.X = 0;
        coord.Y = 0;
        return coord;
    }
}
commented: Code tags on first post. +13

for windows console programs:

include the header file <windows.h>

//get the current position of cursor
COORD getpos()
{
    CONSOLE_SCREEN_BUFFER_INFO csbi;
	COORD coord;

    if(GetConsoleScreenBufferInfo (
        GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
    {
        coord.X = csbi.dwCursorPosition.X;
        coord.Y = csbi.dwCursorPosition.Y;
        return coord;
    }
    else
    {
        coord.X = 0;
        coord.Y = 0;
        return coord;
    }
}

talhaz has the right idea, but that code may be confusing and it doesn't set the console cursor position.

If you're using windows, you can write yourself a couple of helper functions, here's one to set the cursor position.

void SetPos(int x, int y) {
  static HANDLE hOut = GetStdHandle( STD_OUTPUT_HANDLE );
  COORD pos = {x, y};
  SetConsoleCursorPosition( hOut, pos );
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.