C ++打印速度缓慢但在用户按下输入或任何内容时跳过。不应该等待

时间:2018-04-04 19:58:26

标签: c++ linux

我这里有一个C ++函数:

void printTextSlowly(string &s, int speed)
{
    int position = 0;
    for(char c: s)
    {
        position++;
        std::this_thread::sleep_for(std::chrono::milliseconds(speed));
        std::cout << c << std::flush;

        // Should run until user presses enter.
        //if(cin.ignore())
        //{
        //    std::string subString = s.substr(position);
        //    std::cout << subString << std::endl;
        //    break;
        //}
    }
}

所以基本上这会减慢它所做的文本,但是当用户按下回车时,它应该停止并打印出其余的文本。使用cin.ignore(),它等待用户做某事。我不想等它。

非常感谢帮助。

2 个答案:

答案 0 :(得分:0)

1)将String复制到一个新变量中(直到打印完毕)。

2)使用do-while循环,直到用户按Enter键。

3)在结束do-while循环后找出剩余的字符串并打印。

希望有所帮助:)

答案 1 :(得分:0)

编辑:选择已过时。请改用pool

你想要的是等待一段特定的时间,或者直到你在stdin上有什么东西。

由于您使用的是Linux,因此可以使用select来实现。

int select(int nfds, fd_set *readfds, fd_set *writefds,
                     fd_set *exceptfds, struct timeval *timeout);
     

select()和pselect()允许程序监视多个文件          描述符,等待一个或多个文件描述符变为          “准备好”用于某类I / O操作

您不需要多个文件选择器。只是斯坦丁。并将超时设置为1毫秒。

由于我没有Linux方便,这里有一些未经测试的代码改编自链接页面示例和您的示例:

fd_set rfds;
struct timeval tv;
int retval;

/* Watch stdin to see when it has input. */

FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);

/* Wait 1 millisecond. */

tv.tv_sec = 0;
tv.tv_usec = 1000;

int position = 0;

for (int position = 0; position < s.length(); ++position)
{
    retval = select(1, &rfds, nullptr, nullptr, &tv);

    if (retval == -1)
    {
       perror("select()");
       // exit or throw or deal with error
    }
    else if (retval)
    {
       // Data available on cin (user pressed enter)

       std::string subString = s.substr(position);
       std::cout << subString << std::endl;
       break;
    }
    else
    {
       // No data on cin, continue printing
       std::cout << s[position] << std::flush;
    }
}
相关问题