I have a project that I am working on using Dev-C++ as the IDE and Windows as the operating system. As the project is restricted in complexity due to size constraints and current knowledge, I would prefer to avoid using GetAsyncKeyState
and threading unless there is a fairly simple (less than 10 lines) approach I could use.
My program currently displays text using the Text
function using strings and outputting them to the console window. I want to implement a feature that would allow the user to press a key, and allow the text to print out without waiting for the function to read the entire string.
For example:
"Welcome to ..." [user presses space bar while the text is slowly being displayed character by character]
"Welcome to my program! This was developed by me!" [entire string is displayed]
Code:
void Text(string input)
{
int x = 0;
for(int i = 0; i <= 3; i++) //decides when to stop running based on number of strings
{
while (input[x] != '\0')
{
if(input[x] == '.' || input[x] == '!')
{
cout << input[x];
Sleep(375);
cout << " ";
x++;
}
else if(input[x] == '*')
{
Sleep(375);
cout << endl;
x++;
}
else if(input[x] == '~')
{
Sleep(2000);
system("CLS");
x++;
}
else
{
cout << input[x];
Sleep(75);
x++;
}
}
}
}
No, you cannot in a portable way. The reason is that standard I/O on the usual consoles wait for a line to be completed, so you cannot capture single characters as soon as they are typed.
You can achieve that with non-standard functions, though! See Capture characters from standard input without waiting for enter to be pressed