C++ Bug in program
3 posts
• Page 1 of 1
C++ Bug in program
This program is not working... it doesnt show anything on the screen, then it goes in an endless loop. This is a class assignment, and the tyeacher is stumped. Any ideas?
- Code: Select all
#include <iostream.h>
#include <conio.h>
#include <lvp\random.h>
#include <windows.h>
//-----------------------------------------------
void gotoxy(int xpos, int ypos)
/* requires the use of the library windows.h */
{
COORD scrn;
HANDLE hOuput = GetStdHandle(STD_OUTPUT_HANDLE);
scrn.X = xpos; scrn.Y = ypos;
SetConsoleCursorPosition(hOuput,scrn);
}
//-----------------------------------------------
int main()
{
// Randomize();
cout << "Doodler!Press I/J/K/M to move, Q to quit\n";
char KeyPressed;
int x = 40; int y = 10;
do
{
gotoxy(x, y);
cout << '*';
gotoxy(x, y);
KeyPressed = getch();
if (KeyPressed == 'I' || KeyPressed == 'i')
y--;
else if (KeyPressed == 'M' || KeyPressed == 'm')
y++;
else if (KeyPressed == 'J' || KeyPressed == 'j')
x--;
else if (KeyPressed == 'K' || KeyPressed == 'k')
x++;
else if (KeyPressed == 'Q' || KeyPressed == 'q')
;
else
cout << "\a";
} while ((KeyPressed != 'Q') && (KeyPressed != 'q'));
gotoxy(1, 1);
system("cls");
cout << "Random stars! Press any key to stop.\n";
while (!kbhit())
{
gotoxy(1 + random (6), 2 + random(20));
cout << "*";
}
return(0);
}
- coreyw2000
- PROfessional Member
- Posts: 4644
- Joined: Tue Oct 05, 2004 5:30 am
- Location: Saskatchewan, Canada
cout << '*';
If cout is expecting a string, then this may be your problem. Single quotes generates a single character with no null-termination. Double quotes generates a null teminated array. Again, if cout is expecting a string (i.e. null-terminated array) then using single quotes will not guarantee a null-termination and the program will continue to output characters to cout until it finds a null.
So, instead of cout << '*';, try cout << "*";
Also, instead of using a bunch of if..else statements, it may be more readable to use a switch statement in the do..while loop.:
switch( getch() )
{
case 'I':
case 'i':
y--;
break;
case 'J':
case 'j':
x--;
break;
|
|
|
default:
cout << "\a";
}
-GP
What, me worry?
- Luck is the residue of proper planning...
- Luck is the residue of proper planning...
3 posts
• Page 1 of 1
Return to HTML, CSS, and Scripts
Who is online
Users browsing this forum: No registered users and 2 guests