2017-05-08 98 views
0

我編寫了一個程序,讓用戶鍵入單詞並將它們保存到char數組中,直到用戶輸入「* end」。如何在用戶按下時停止程序Ctr + Z而不是輸入「*結束」?將鍵盤快捷鍵添加到控制檯應用程序中C

下面是代碼

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'。谷歌處理信號在C – Dunno

+0

看看這個http://stackoverflow.com/questions/16132971/how-to-send-ctrlz-in-c –

回答

0

這裏的返回值是什麼manscanf()說,關於返回值(不是參數值)

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. 

這是什麼歸結爲:

總是檢查從系統函數返回的錯誤條件。

建議更改此:`

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

到:

始終使用MAX CHARACTERS改性劑比所述輸入緩衝器的長度少一個,以避免緩存器溢出。這種緩衝區溢出是未定義的行爲,並可能導致seg故障事件。

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 
1

使用的scanf

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