Rate my typewriter affect

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

void typewrite(std::string wow, double wait = 100){
for(int i = 0; i <= wow.length() ; i++){
system("cls");
std::cout << wow.substr(0,i);
Sleep(wait);
//You can add a beep()
}
}

int main(){
std::string wow;
std::getline(std::cin, wow);
typewrite(wow);

}
Last edited on
To be able to test your code on Linux I had to do the following changes.

#include <windows.h> -> #include <unistd.h>

system("cls"); -> system("clear");

Sleep(wait); -> usleep(wait * 1000);

I also had to use std::flush after outputting the substring otherwise nothing was printed inside the loop, instead everything got printed when the program terminated. Not sure if this is necessary on Windows (maybe Sleep and/or system automatically flush on Windows) but I don't think it hurts adding it just in case.

 
std::cout << wow.substr(0,i) << std::flush;

This worked very well except that there was some flickering. To avoid this you could remove the call to system("cls"); and output only one character wow[i] each time instead of the whole substring.

 
std::cout << wow[i] << std::flush;
Topic archived. No new replies allowed.