5

ユーザー入力のために一時停止する簡単なコマンドを作成しようとしています。Bash スクリプトで役立つと思います。

これが私のコードです:

#include <stdio.h>
int main() {
  char key[1];
  puts("Press any key to continue...");
  fgets(key,1,stdin);
}

ユーザー入力のために一時停止することさえありません。

以前に getch() (ncurses) を使用しようとしました。何が起こったのかというと、画面が空白になり、キーを押すと元の画面に戻り、次のように表示されました。

$ ./pause
Press any key to continue...
$

ちょっと欲しかったものです。しかし、私が欲しいのは、pauseDOS/Windows (私は Linux を使用しています) のコマンドに相当するものだけです。

4

3 に答える 3

15

GNU C ライブラリ マニュアルから:

関数: char * fgets (char *s, int count, FILE *stream)

fgets 関数は、ストリーム stream から改行文字まで (改行文字を含む) の文字を読み取り、それらを文字列 s に格納し、文字列の末尾を示す null 文字を追加します。s には count 文字相当のスペースを指定する必要がありますが、読み取られる文字数は最大で count − 1です。余分な文字スペースは、文字列の末尾にヌル文字を保持するために使用されます。

したがって、fgets(key,1,stdin);0 文字を読み取って戻ります。(読む: すぐに)

代わりにgetcharまたはを使用してください。getline

編集: ストリームで文字が使用可能になると fgets も返されずcount、改行を待機し続けてからcount文字を読み取るため、この場合、「任意のキー」は正しい表現ではない可能性があります。

次の例を使用して、行バッファリングを回避できます。

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch ( void ) 
{
  int ch;
  struct termios oldt, newt;
  
  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
  
  return ch;
}

int main()
{
    printf("Press any key to continue.\n");
    mygetch();
    printf("Bye.\n");
}
于 2012-05-13T21:50:12.357 に答える
2

投稿の下にコメントを追加する方法がわからないので、これは実際には回答ではなくコメントです。

In linux Stdin is buffered so you need to flush it which is what pressing 'enter' does on your terminal. It seems you want to read from an unbuffered stream i.e you want to react to a keypress imediately (without the need to explicitly flush it).

You can create your own unbuffered stream using a file discriptor and then read from it using "getc", you may have to use termios to setup unbuffered input as others have suggested.

于 2012-05-14T06:21:16.593 に答える