Search code examples
c++functionclassvoidcout

Problem with calling a function with another function (both within classes). No error codes C++


class DatingSim
{
public:
    string userName;
    int userAge;
    int day1Place;
    string places[4] = { "Coffee Shop", " Duck Pond", "Club" , "Class"};
    string dayOneA = "W E L C O M E  T O  D A T I N G  G A M E";


    void slowPrint(string str, int time)
    {
        for (size_t i = 0; i != str.size(); ++i) 
        {
            cout << str[i];
            Sleep(time);
        }
    }
    void dayOne();

void DatingSim::dayOne()
{

    slowPrint(dayOneA, 250);
    cout << endl;

... other code (just cout stuff shouldn't be a problem)
}

int main()
{
    DatingSim NEWGAME;
    NEWGAME.dayOne();

    return 0;
}

So previously instead of a string for the slowprint function parameter I was using a string array but it wasn't working so I switched to just string and it didn't work. I tested it and it works when it's not within a class together. Should I not use a class? I'm creating a little game and I'd rather be able to use a class. No error messages just says FAILED when I try to run.


Solution

  • As suggested, you need to flush the output stream after each letter, otherwise you'll see the entire string printed out at the end.

    #include <chrono>
    #include <iostream>
    #include <string>
    #include <thread>
    
    using namespace std;
    
    class DatingSim {
    public:
        string userName;
        int userAge;
        int day1Place;
        string places[4] = { "Coffee Shop", " Duck Pond", "Club" , "Class"};
        string dayOneA = "W E L C O M E  T O  D A T I N G  G A M E";
    
        void slowPrint(string str, int time)
        {
            for (size_t i = 0; i != str.size(); ++i) 
            {
                cout << str[i] << flush;
                this_thread::sleep_for(chrono::milliseconds(time));
            }
        }
    
        void dayOne()
        {
            slowPrint(dayOneA, 250);
            cout << endl;
        }
    };
    
    int main()
    {
        DatingSim NEWGAME;
        NEWGAME.dayOne();
        return 0;
    }