2017-05-08 9 views
0

ユーザーが "* end"と入力するまで、ユーザーが単語を入力してchar配列に保存するプログラムを作成しました。 "* end"と入力する代わりにCtr + Zを使用しますか?Cのコンソールアプリケーションにキーボードショートカットを追加

は、ここでそれは、特定のoperating system可能性がコード

char text[1000][100]; 

char end[100] = "*end"; 
int count =-1; 


do 
{ 
    count++; 
    scanf("%s",&text[count]); 



}while(strcmp(text[count],end)==1); 
+1

「Ctr + Z」がエミュレートする環境を確認してください。 scanf()の返り値を比較すると、 –

+0

あなたが送信するシグナル、すなわち 'SIGTSTP'を処理する必要があります。 GoogleでCのシグナルを処理するために – Dunno

+0

これを見てくださいhttp://stackoverflow.com/questions/16132971/how-to-send-ctrlz-in-c –

答えて

0

の戻り値はscanf()ためmanページが返された値(ないパラメータ値)について言っていることである使用

これはつまるところ何
RETURN VALUE 
    On success, these functions return the number of input items success‐ 
    fully matched and assigned; this can be fewer than provided for, or 
    even zero, in the event of an early matching failure. 

    The value EOF is returned if the end of input is reached before either 
    the first successful conversion or a matching failure occurs. EOF is 
    also returned if a read error occurs, in which case the error indicator 
    for the stream (see ferror(3)) is set, and errno is set to indicate the 
    error. 

システム機能から返されるエラー条件を常にチェックします。常にバッファのオーバーフローを回避するために、入力バッファの長さよりも1つ少ないMAX文字修飾子を使用

:に `

scanf("%s",&text[count]); 

は、これを変更示唆しています。このようなバッファオーバーフローは未定義の動作であり、segaultイベントにつながる可能性があります。

int retScanf = scanf("%99s", &text[count]); 

switch(retScanf) 
{ 
    case 1: // normal return 
     // handle string input 
     // this is where to check for 'end' 
     break; 

    case EOF: // ctrl-z return 
     // user entered <ctrl>-z 
     break; 

    case 0: // invalid input return 
     // user entered only 'white space' (space, tab, newline) 
     break; 

    default: // should always provide for unexpected 'switch case' 
     // display error message here 
     break; 
} // end switch 
3

です。 C11(またはC++ 14)標準約tty demystifiedtermios(3)を読んで、いくつかの使用を検討、などについてterminals(またはterminal emulators)またはキーボード、たったの約standard output、標準入力、... Linuxの

を知りませんライブラリncursesまたはreadlineのように。

ところで、配列の配列を使用する代わりにC dynamic memory allocationを使用することをお勧めします。結果のカウントはscanf(3)である必要があります。 strdup & asprintfをご覧ください。

1

ここscanf

do { 
    count++; 
    if (scanf("%s", &text[count]) != 1) break; 
} while (strcmp(text[count], end) != 0); 
関連する問題