challenge 出力の一時停止と再開

起動すると、標準出力に1秒毎に'a'の1文字を出力し続けるプログラムで、 以下の条件を満たすものを「どう書く?」

  • 'q'キーが押されるとプログラムは終了する
  • 出力中に'p'キーが押されると一時停止する
  • 一時停止中に'p'キーが押されると出力を再開する

Posted feedbacks - C++

こんにちは。 このコードは環境に依存しています。標準ではありません。 でも、C/C++だとstdioもiosteamもブロッキングされちゃうのでこういうコード書くしか手がないと思われます。 抜け道募集。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <stdio.h>
#include <conio.h>

int main(){
    bool Output=true;
    int ch=0;
    do{
        ch = 0;
        if(_kbhit()) ch  = _getch();//環境依存コード。
        if(ch == 'p') Output = !Output;
        if(Output) printf("A");
    }while(ch != 'q');

}

うーん。こんにちは。 えらそうなこと言っておきながら仕様満たしてなかったですね。 1秒毎に表示するようにしました。 ほかの方などがいわれてるの見て気づいたんですけど、あるぅぇえええ??って感じです。(汗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <time.h>
#include <conio.h>

int main(){
    bool IsOutput=true;
    int ch=0;
    int TimeCount=0,TimeOld=0;
    do{
        ch = 0;
        if(_kbhit()) ch  = _getch();//環境依存コード。
        if(ch == 'p') IsOutput = !IsOutput;
        if(IsOutput){
            TimeCount = time(NULL);
            if(TimeCount != TimeOld){
                printf("A");
                TimeOld = TimeCount;
            }
        }
    }while(ch != 'q');
    return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...