Hello! I'm a student at a game programming course in Sweden and I've recently started to begin learning c++ in my spare time. First post here, so please be gentle. ;)
For now I'm trying to make a simple dialogue game in the console window, and I'm trying to make my output text look as if someone is typing it to you. I've only managed to make words appear one at a time but what I'm trying to do is to make each letter of every word to appear one after the other. My code looks like this:
#include <iostream>
#include <unistd.h> // include <windows.h> on windows
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
usleep(60000); // use Sleep on windows
}
}
int main()
{
type_text("Hej hej hallÄ!");
}
How to erase text I don't know. It's not possible with standard C++ so you have to use system/library functions for that.
Thank you very much! The function type_text works incredibly. I have a few questions though:
I know that this "::" operator, after std refers to a built in class. But what's the purpose of "&" after "string". Is "text" another type just like "string" or are you making "text" a string type? And I've never heard of "std::flush" before, could you clarify what that is?
Almost everything in the standard library is in the std namespace. That's why I write std:: infront of everything. In your code you wrote usingnamespace std;, that makes so you don't have to write std::. The & after string means it's a reference to a string. If you don't use a reference it will create a copy of the string which is slower. Inside the function we can use text like a normal string. When writing output the text will not always be updated right away. It might not be visible until a complete line is written. std::flush just makes so that all written output will be visible now and not later.