2017-11-04 54 views
0

cout과 비슷한 역할을하는 개체를 만들려면 this_thread::sleep_for()을 사용하여 테스트하고 있습니다. 단, 문자열을 인쇄 할 때 각 문자 사이에 약간의 지연이 있습니다. 그러나 각 문자 사이에 0.1 초를 기다리지 않고 약 1 초 정도 기다렸다가 한 번에 모두 인쇄합니다. 내 코드는 다음과 같습니다.이 코드가있는 this_thread :: sleep_for?

#include <iostream> 
#include <chrono> 
#include <thread> 

class OutputObject 
{ 
    int speed; 
public: 
    template<typename T> 
    void operator<<(T out) 
    { 
     std::cout << out; 
    } 
    void operator<<(const char *out) 
    { 
     int i = 0; 
     while(out[i]) 
     { 
      std::this_thread::sleep_for(std::chrono::milliseconds(speed)); 
      std::cout << out[i]; 
      ++i; 
     } 
    } 
    void operator=(int s) 
    { 
     speed = s; 
    } 
}; 

int main(int argc, char **argv) 
{ 
    OutputObject out; 
    out = 100; 
    out << "Hello, World!\n"; 
    std::cin.get(); 
    return 0; 
} 

내가 뭘 잘못하고 있는지 아는 사람이 있습니까?

편집 : CoryKramer는 실시간으로 작동하려면 std :: flush가 필요하다고 지적했습니다. std::cout << out[i];std::cout << out[i] << std::flush;으로 변경하면 문제가 해결되었습니다.

+2

'while' 내에 ['std :: flush'] (http://en.cppreference.com/w/cpp/io/manip/flush)하면됩니다. loop – CoryKramer

+0

'std :: cout'의 출력은 * buffered *임을 기억하십시오. –

답변

2

스트림 버퍼, 그래서 cout 또한 스트림 cin에 자동으로 버퍼를 플러시 데이터를 호출 예를 들어, 플러시 스트림 전에 endl 플러시 스트림을 텍스트를 인쇄하고 '\n'를 추가하지 않습니다. 이것을 사용해보십시오 :

while(out[i]) 
{ 
    std::this_thread::sleep_for(std::chrono::milliseconds(speed)); 
    std::cout << out[i]; 
    std::cout.flush(); 
    ++i; 
}