x and y wont work

Hello here is my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <windows.h>

using namespace std;

void z()
{
    Sleep(500);
}

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;

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

void homeCursor(HANDLE h)
{
    COORD home = { 0, 0 };
    SetConsoleCursorPosition(h, home);
}

int main()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    std::srand((unsigned) std::time(0));

    const char a [] = { 'o', 'O', 'o', 'O', '\0' };
    const char b [] = { 'O', 'o', 'O', 'o', '\0'};

    const char* row [] = { a, b};

    const unsigned rows = 10;

    for (unsigned i = 0; i < 10; i++)
    {
        homeCursor(hConsole);

          if (i % 2)
        {
            int a = 6;
             SetConsoleTextAttribute (hConsole, a);
            for (unsigned j = 0; j < rows; ++j)
                gotoXY(14,13);              //this doesnt work out too well
                std::cout << row[j % 2] << '\n';
        }
        else
        {
            int b = 3;
             SetConsoleTextAttribute (hConsole, b);
            for (unsigned j = 0; j < rows; ++j)
                gotoXY(14,13);               //this doesnt work out either...
                std::cout << row[1 - (j % 2)] << '\n';

        }

        std::cout << flush;

        z();
    }
}

It works out well until lines 50 and 58. Normally in my other programs "gotoXY" allows me to set the position of the display. However, it won't work for this one. Why is this and how do I fix it?
Last edited on
I'm not qualified to answer your question as I haven't used the Windows API in a long time. However, I'd still like to bug you about something.

This thread should be in the Windows programming section as you're using stuff from the Windows API. You'll be much more likely to get a response there.

-Albatross
@megasnorlax..

The problem you're having is because the variable 'j' is out of scope,. Without the brackets after a for loop, only the first line would be executed, which is your 'gotoXY(14,13);'. Now your program doesn't understand the 'j' anymore. To remedy that, encompass everything you want executed in the for loop, with brackets, and things will look great. I liked the way the O's danced back and forth.
1
2
3
4
5
for (unsigned j = 0; j < rows; ++j)
{
	gotoXY(14,13);              // It will now
       std::cout << row[j % 2] << '\n';
}


And do the same for lines 58 and 59
Thanks a lot. It works great now.
Topic archived. No new replies allowed.