Reputation: 39
I was making a console game with C on Visual Studio 2019. I made a code that print a variable.
It works only when value is greater than 10 .
If value of variable is less than 10 it prints 10 instead of 1, 2 instead of 20 ... 9 instead of 90.
I have no idea how to solve this problem.
Here is my code
#include<stdio.h>
#include<windows.h>
int a =20;
void gotoxy(int x, int y) { //cursor goes to x, y
COORD CursorPosition = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), CursorPosition);
}
void HideCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = FALSE;
SetConsoleCursorInfo(consoleHandle, &info);
}
void count() {
char c = _getch();
switch (c) {
case 'p': a++; break;
case 'o': a--; break;
}
}
int main() {
system("mode con cols=10 lines=10");
system("cls");
HideCursor();
while (1) {
gotoxy(5, 5);
count();
printf("%d", a);
}
}
Upvotes: 1
Views: 69
Reputation: 409166
It's because you don't overwrite the second digit if a
becomes a single-digit number. You need to overwrite all previously written digits, for example by setting a field width:
// Print right-justified numbers, with empty spaces for one or two digit numbers
printf("%3d", a);
Upvotes: 5