为什么 sleep 不等待,无论括号中输入的值有多高?

Why does sleep not wait, no matter how high the value entered in the parentheses is?

我正在尝试重写一个我之前用 C++ 编写的程序,该程序根据用户输入的内容通过 ssh 或 sftp 连接到我的笔记本电脑,该程序运行良好,但我正在尝试编写 std::cout 逐个字母输出,字符之间有 200 毫秒的延迟。 这是我目前的尝试(无效):

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>

int main()
{
std::cout << "S";
sleep(0.2);
std::cout << "S";
sleep(0.2);
std::cout << "H";
sleep(0.2);
std::cout << " o";
sleep(0.2);
std::cout << "r";
sleep(0.2);
std::cout << " S";
sleep(0.2);
std::cout << "F";
sleep(0.2);
std::cout << "T";
sleep(0.2);
std::cout << "P";
std::cout << "?\n" << ">"; 

std::string contype;
std::cin >> contype;
if(contype == "ssh")
{
system("ssh redacted");
}
if(contype == "sftp")
{
system("sftp redacted");
}
}

如果你使用的是c++11,你应该使用thread和chrono休眠200ms。

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <chrono>
#include <thread>

int main()
{
std::cout << "S" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "S" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "H" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << " o" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "r" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << " S" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "F" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "T" << std::flush;
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << "P" << std::flush;
    std::cout << "?\n" << ">";

std::string contype;
std::cin >> contype;
if(contype == "ssh")
{
system("ssh redacted");
}
if(contype == "sftp")
{
system("sftp redacted");
}
}

应该可以正常工作。 编辑:您应该在每个输出的末尾输出 std::flush 以显式刷新缓冲区。

编辑 2:如评论中所述,定义一个常量而不是在每次迭代时使用幻数更好。另一种选择是定义一个遍历字符串并打印每个字母的函数,然后等待。这会像这样 -

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <chrono>
#include <thread>

void printAndSleep(const std::string& msg, int timePeriod);

int main()
{
    const std::string msg = "SSH or SFTP";
    const int waitingTime = 200;
    printAndSleep(msg, waitingTime);
    std::cout << "?\n" << ">";

std::string contype;
std::cin >> contype;
if(contype == "ssh")
{
system("ssh redacted");
}
if(contype == "sftp")
{
system("sftp redacted");
}
}

void printAndSleep(const std::string& msg, int timePeriod){
    for (char c : msg) {
        std::cout << c << std::flush;
        std::this_thread::sleep_for(std::chrono::milliseconds(timePeriod));
    }
}