blvrryfox
blvrryfox

Reputation: 17

Output letters one at a time in C++?

I've seen a couple of solutions to this question, but I'm still running into an issue. I've tried several of the solutions I've seen on this site, but I keep having the same issue. I'm not sure how to make this work, and I'm also not sure why it's not working, since I'm really new to C++.

A brief explanation of what I am attempting to do: I'm writing a simple old-school text-based story/game for a video game design club at my school, and at several points I have the user make decisions, or input things such as their name, which is then used in an output line, as it would be referenced several times. I have had no problem doing that, using something simple like this:

#include <iostream>
#include <string>
#include <limits>
#include <windows.h>
using namespace std;


int main(){

   string name, place ;
   cout << "???: What is your name? ";
   getline (cin, name);
   cout << "???: Hello, " << name << "!\n" << "\n";
}

My problem is that I'd like to have the text appear one character at a time, like dialogue, but whenever I try to use something I've seen written by others, it doesn't seem to like it very much. The only one that I tried that I can now find again is 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å!");
}

Apparently there is some sort of conflict regarding my attempt to output the name back to the user when I try to use that code with what I've written. I'm not really sure what the problem is, since I'm so new to C++, can anyone help me out?

Upvotes: 0

Views: 2849

Answers (1)

vsoftco
vsoftco

Reputation: 56567

Consider using std::this_thread::sleep_for, as it is standard C++11. Example:

#include <iostream>
#include <thread> // standard C++11

// 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
        std::this_thread::sleep_for(std::chrono::milliseconds(60));
    }
}
int main()
{
    type_text("Hello, World!");
}

If you have access to a C++14 compiler, you can simply make use of the std::chrono user-defined literals and have a more "natural" syntax:

using namespace std::literals;
std::this_thread::sleep_for(60ms);

Upvotes: 1

Related Questions