Page 1 of 1

C++ Typewriter text effect (xcode)

Posted: Fri Apr 02, 2010 11:15 am
by TheThirdL3g
I am making a console app (using a mac and xcode), and I wanted to add a typewriter effect to text. I thought it would be a pretty simple task, but when I run the app the console freezes when it reaches the function. It still accepts user input, but it doesn't continue.

Code: Select all

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

string ptext;
void twtext(char[]);

int main (int argc, char * const argv[]) {
    twtext("Typewriter effect test\n");
	
	cin >> ptext;
    return 0;
}

void twtext(char text[]) {
	for (int i = 0; i < strlen(text); i++) {
		cout << text[i];
		sleep(200);
	}
}

Any help would appreciated.

Re: C++ Typewriter text effect (xcode)

Posted: Fri Apr 02, 2010 11:22 am
by M_D_K
that's cause sleep() takes seconds not milliseconds. you'd need to use something like nanosleep

Re: C++ Typewriter text effect (xcode)

Posted: Fri Apr 02, 2010 12:11 pm
by TheThirdL3g
Thanks for the help. Nanosleep worked for delaying, but it for some reason when the timer is up instead of only printing one letter it prints the whole line of text.

Even when I use a while loop for a delay it does the same thing.

The code is showing the use of the while loop with the nanosleep method commented out.

Code: Select all

#include <iostream>
#include <string>
#include <time.h>

using namespace std;

string ptext;
void twtext(char[]);
void msleep(int);

int main (int argc, char * const argv[]) {
    twtext("Typewriter effect test\n");
	
	cin >> ptext;
    return 0;
}

void twtext(char text[]) {
	for (int i = 0; i < strlen(text); i++) {
		cout << text[i];
		int x = 0;
		while (x < 9999999) {
			x++;
		}
		//msleep(200);
	}
}

void msleep(int ms) {
	struct timespec time;
	time.tv_sec = ms / 1000;
	time.tv_nsec = (ms % 1000) * (1000 * 1000);
	nanosleep(&time,NULL);
}

Re: C++ Typewriter text effect (xcode)

Posted: Fri Apr 02, 2010 1:00 pm
by M_D_K
I forgot to mention that you're not flushing stdout this can be done using std::endl. BUT that would also create a new line what you want to do is use fflush(stdout) which is in cstdio

Code: Select all

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>

using namespace std;

string ptext;
void twtext(char[]);
void msleep(int);

int main (int argc, char * const argv[]) {
    twtext("Typewriter effect test\n");
   
   cin >> ptext;
    return 0;
}

void twtext(char text[]) {
   for (int i = 0; i < strlen(text); i++) {
      putchar(text[i]);
      fflush(stdout);
      msleep(200);
   }
}

void msleep(int ms) {
   struct timespec time;
   time.tv_sec = ms / 1000;
   time.tv_nsec = (ms % 1000) * (1000 * 1000);
   nanosleep(&time,NULL);
}
Also if you want it to look more like a person is typing you could throw a little randomness into the delay (not much).