Print a variable in my gotoXY routine

I created a gotoXY() routine so that I can print my text at any location on the screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using namespace System;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;

void gotoXY(int x, int y) 
{ 
CursorPosition.X = x; 
CursorPosition.Y = y; 
SetConsoleCursorPosition(console,CursorPosition); 
}

void gotoXY(int x, int y, string text) 
{ 

CursorPosition.X = x; 
CursorPosition.Y = y; 
SetConsoleCursorPosition(console,CursorPosition);
cout << text;
}


1
2
gotoXY(5,7);
cout << "Hello World!";


This of course will print the text at column 5, row 7. That part works great. Now comes the part I can't get working.

1
2
3
4
int x=5;
int y=7;
string text = "Printing at column " << x << ", row " << y << ".";
gotoXY(x,y, text);


It should print text at 5,7, but doesn't. Could sure use some of the C++ expertise in this forum.

Thanks

whitenite1
I'm not sure why your code don't work but i tried this and it worked fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>

void goTo(int x, int y){
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;

    pos.X = x;
    pos.Y = y;

    SetConsoleCursorPosition(hConsole, pos);
}

int main()
{
    goTo(10, 10);
    printf("This works!\n");
    return 0;
}
Thanks, but I already knew the first part of my routine works. I use it a lot in my programs. It's the second part of gotoXY that doesn't. I am wanting to send to the x,y coordinates, a string that has variables in it.

I have tried it three ways :
1 : string text = "This is printing at " << x << " and at " << y << ".";
gotoXY(3, 7 , text);

2: gotoXY(3, 7, "This is printing at " << x << " and at " << y << ".");

3: gotoXY(3, 7, "This is printing at " + x + " and at " + y + ".");

All I get are errors. Is there an easy way make the integer variables a part of the string, so it can be printed along with the text?

( I think I should not have put the first part of gotoXY(x , y) under the code label, and only printed the gotoXY(x,y,text) part. Sorry for any misconstrued info.. )

whitenite1
It looks like you could use a stringstream.

1
2
3
4
5
6
7
8
9
10
11
#include <sstream>

//...

std::stringstream buffer;

buffer << "Printing at column " << x << ", row " << y << ".";

gotoXY(x, y, buffer.str());

//... 

Useful link -> http://cplusplus.com/reference/iostream/stringstream/
Last edited on
Thank you. That solved the problem.

whitenite1
Topic archived. No new replies allowed.