reducing count with each typed character

Hello everyone.

I've a question whose solution I can't figure out at all.
The question is:

Suppose I declare int count =140
Now I want my program to be such that whenever I press a key on keyboard, the count should decrease by one, in the same way that we see on twitter. It should be visible as I type, not on EOF.

How can I do that?
Anyone? Please help me.
@Gamemaster007

Here's something I threw together. Hope it helps.

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
// Reduce count.cpp : main project file.

#include <iostream>
#include <string>
#include <conio.h>
#include <windows.h>

using std::cout;
using std::cin;
using std::endl;
using std::string;

void gotoXY(int x, int y);

int main()
{
 int count =25;
 char letter;
 string sentence;
 cout << "Please type a sentence up 25 characters long.." << endl;
 do
 {
	letter = _getch();
	if (count != 0 && count < 26)
	{
	 count--;
	 sentence+=letter;
	 gotoXY(0,12);

	 if (letter == '\x08' && count < 24)
		count+=2;
	 cout << sentence << " (Letters remaining.. " << count << ") ";
	 gotoXY(0,1); // Put cursor back to top
	}

 }while (count>0);
 return 0;
}

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


Last edited on
@whitenite1

Thanks for the code. It's working, but can it be done without using windows.h?
I'm a beginner and not familiar with windows.h header file.
@Gamemaster007

The windows.h header file is used here, for the gotoXY() function. If you leave that out, and the calls to it, yes, the program still works, except that each new sentence will be printed on a separate line. You would also need to add an << endl; after cout << sentence << " (Letters remaining.. " << count << ") ";

OR, it could be done using the '\b' command, which moves the cursor back a space. string back(10,'\b') would create 10 '\b', etc.

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
#include <iostream>
#include <string>
#include <conio.h>
//#include <windows.h>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
 int count =25;
 char letter;
 string sentence;

 cout << "Please type a sentence up 25 characters long.." << endl;
 do
 {
	letter = _getch();
	if (count != 0 && count < 26)
	{
	 count--;
	 sentence+=letter;
	 
	 if (letter == '\x08' && count < 24)
		count+=2;
	 string back(52-count,'\b'); // 52-count equals the length of ' (Letters remaining.. " << count << ") '
	 cout << back << sentence << " (Letters remaining.. " << count << ") ";
	}

 }while (count>0);
 return 0;
}
Last edited on
Topic archived. No new replies allowed.