Comment detail

出力の一時停止と再開 (Nested Flatten)

こんにちは。 このコードは環境に依存しています。標準ではありません。 でも、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;
}
ども、raynstardです。
入力がブロッキングされてしまうのは
入力モードを変更してあげないからですね。

UNIXでgetche()の作り方というのを調べるといろいろと出てくると思います。
ポイントはtermiosでカノニカルモードを解除してあげていることと
標準出力のバッファリングをなしにしているところでしょうか?
標準入力の方はおまけです。
// gcc -Wall -std=c99 doukaku179.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <stdbool.h>
#include <termios.h>
#include <time.h>

static struct termios termios_save;
static bool isContinued = true;
static bool enableOutputScreen = true;

int initKeyInput(void)
{
    struct termios t;
    tcgetattr(0, &termios_save);
    tcgetattr(0, &t);
    t.c_lflag &= ~(ICANON|ECHO);
    t.c_cc[VMIN]  = 0;
    t.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &t);
    setvbuf(stdin, NULL, _IONBF, 0);
    return 0;
}

int main(int argc, char *argv[])
{
    char key;
    ssize_t read_size;
    time_t old, now;

    initKeyInput();
    setvbuf(stdout, NULL, _IONBF, 0);

    old = 0;
    while( isContinued )
    {
        now = time(NULL);
        if( now != old )
        {
            old = now;
            if( enableOutputScreen == true )
            {
                printf("a");
            }
        }
        read_size = fread(&key, 1, sizeof(key), stdin);
        if( read_size > 0 )
        {
            switch( key )
            {
                case 'q':   /* quit */
                    isContinued = false;
                    break;
                case 'p':   /* pause */
                    enableOutputScreen = (enableOutputScreen != true);
                    break;
                default:
                    break;
            }
        }
    }
    tcsetattr(0, TCSANOW, &termios_save);
    printf("\n");
    return 0;
}
/* EOF */

Index

Feed

Other

Link

Pathtraq

loading...