c++ - 用另一个函数调用一个函数的问题(都在类中)。没有错误代码 C++

标签 c++ function class void cout

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;
}

所以之前我使用的是字符串数组而不是 slowprint 函数参数的字符串,但它不起作用,所以我切换到字符串但它不起作用。我测试了它,当它不在一个类(class)时它可以工作。我不应该上课吗?我正在创建一个小游戏,我宁愿能够使用一个类。当我尝试运行时,没有错误消息只是说失败。

最佳答案

如建议的那样,您需要在每个字母后刷新输出流,否则您会看到最后打印出整个字符串。

#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;
}

关于c++ - 用另一个函数调用一个函数的问题(都在类中)。没有错误代码 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59189096/

相关文章:

c++ - 如何注释头文件?

r - 操作 R 中字符列表的列表

python - 将毫秒转换为小时、分钟和秒 python

php - Codeigniter 如何在当前 Controller 中获取所有/特定方法

c++ - 关于调用继承函数

c++ - 无法在 `catch(const std::exception &ex)` 中捕获 std::invalid_argument

c++ - boost multi_index 反向迭代器删除麻烦

c++ - 在 gcc 中启用 "differing levels of indirection"警告/错误

python - 将函数及其参数之一传递给 Python 中的另一个函数

javascript - ES6 WeakMap 类封装