###実現したいこと
指定された時間を経過したことを知らせるタイマーを作成したい
以前作成したプログラム(実行成功ずみ)から少し変更した
###問題点
実行した瞬間にタイマーが終わってしまう。 時をきざんでくれない。
###変更点
タイマーの棒を出力する前に
C++
1 auto now=std::chrono::system_clock::now(); 2 std::chrono::milliseconds ms(int(std::atof(argv[1])/50*1000));
を追加した。
for文の中で
C++
1std::this_thread::sleep_until(now+(i+1)*ms);
に変更をした。
###変更前のコード
C++
1#include<iostream> 2#include<chrono> 3#include<thread> 4#include<cstdlib> 5void sleep(double sec); 6int main(int argc,char* argv[]) 7{ 8 int i; 9 if(argc!=2){ 10 std::cout<<"使い方:"<<argv[0]<<"秒数\n"; 11 std::exit(1); 12 } 13 std::cout<<"0% 10 20 30 40 50 60 70 80 90 100\n"; 14 std::cout<<"|----|----|----|----|----|----|----|----|----|----|\n"; 15 std::cout<<"^"<<std::flush; 16 for(i=0;i<50;i++){ 17 sleep(std::atof(argv[1])/50); 18 std::cout << "\b"; 19 std::cout << "~"; 20 std::cout << "^"; 21 std::cout << std::flush; 22 } 23 std::cout<<"\n"; 24 std::cout<<std::atof(argv[1])<<"秒経過しました\n"; 25 return 0; 26} 27void sleep(double sec) 28{ 29 int msec=sec*1000; 30 std::this_thread::sleep_for(std::chrono::milliseconds(msec)); 31}
###変更後のコード
C++
1#include<iostream> 2#include<chrono> 3#include<thread> 4#include<cstdlib> 5void sleep(double sec); 6int main(int argc,char* argv[]) 7{ 8 int i; 9 if(argc!=2){ 10 std::cout<<"使い方:"<<argv[0]<<"秒数\n"; 11 std::exit(1); 12 }else{ 13 auto now=std::chrono::system_clock::now(); 14 std::chrono::milliseconds ms(int(std::atof(argv[1])/50*1000)); 15 std::cout<<"0% 10 20 30 40 50 60 70 80 90 100\n"; 16 std::cout<<"|----|----|----|----|----|----|----|----|----|----|\n"; 17 std::cout<<"^"<<std::flush; 18 for(i=0;i<50;i++){ 19 std::this_thread::sleep_until(now+(i+1)*ms); 20 std::cout << "\b"; 21 std::cout << "~"; 22 std::cout << "^"; 23 std::cout << std::flush; 24 } 25 } 26 std::cout<<"\n"; 27 std::cout<<std::atof(argv[1])<<"秒経過しました\n"; 28 return 0; 29} 30void sleep(double sec) 31{ 32 int msec=sec*1000; 33 std::this_thread::sleep_for(std::chrono::milliseconds(msec)); 34}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。