I'm trying to print out a character array (carefully choosing my words here) as if it were being typed by someone to the console. For some reason, printf
does not immediately print the character to the console. As-is, the program will have nothing printed to the console for the exact amount of time taken to print the entire character array. However, when I uncomment the line //printf("\n");
, the console will actually show the contents being "typed", although vertically. In other words, using a newline seems to force the console to immediately print the character.
Why is this, and what would be an ideal way to fix this? I ask because I'm trying to think generally: what if I were writing a text-engine for a graphical video game?
#include <stdio.h>
#include <unistd.h>
void milliDelay(unsigned int milliseconds)
{
usleep(milliseconds * 1000);
}
void printConsole(char* txt)
{
//Define local variables such as the iterator and timers
unsigned int i;
unsigned const int keyDelay = 75, puncDelay = 1000;
//Print each character to the screen until we reach the null character
for(i = 0; txt[i] != '\0'; i++)
{
if(txt[i] == '.' || txt[i] == '!' || txt[i] == '?')
{
printf("%c", txt[i]);
milliDelay(puncDelay);
}
else
{
printf("%c", txt[i]);
milliDelay(keyDelay);
}
//printf("\n");
}
//Newline for much more appealing text formatting
printf("\n");
}
int main(int argc, char** argv) {
printConsole("Hello. This is a test using punctuation! Does this pause correctly?");
return 0;
}
For what it's worth, I'm using an Ubuntu system. I have not been able to see if the code works as intended on other platforms. I have also researched this question. I have written the code as I thought of it. Others have used putchar()
, but this is something I never saw in my C programming class--hence I don't use that here. Is there anything bad about using printf()
over putchar()
in such a case?