對不起,這是愚蠢的方式,但我不知道怎麼說技術。如何讓我的程序「忘記」我在鍵盤上按下的字母?
我的程序是打字訓練。如果用戶寫的字母(userWord [i],從鍵盤上用getch())獲得的字母與我給他的單詞中的相應字母不相同,我想發出聲音(filas [maxIndex] [i] )。我的代碼工作正常,除了如果例如我給他「你好」,並且他寫道「heklo」,因爲他寫得非常快,失敗聲音將播放3次(對於k,l,o)。我想以某種方式釋放鍵盤的緩衝區(我認爲這是說「忘記我按下的字母」的技術方式),用戶不用'k','l','o '被存儲並作爲userWord [我],我試過fflush但沒有工作。
我使用Visual Studio
printf("\n\n%s\n", filas[maxIndex]); //Here it prints "Alba"
cont = 1;
while (cont == 1) {
i = 0;
while (userWord[i] != ' ') { // the user presses space to make the program know he has completed his word and wants to go to the next one
while (!kbhit()) {}
fflush(stdin); //I believe this should free the keyboard buffer?
userWord[i] = getch();
printf("%c", userWord[i]); //prints each letter the user writes each time the loop is executed, then he presses space to exit
if (userWord[i] != filas[maxIndex][i]) {
PlaySound(TEXT("failSound.wav"), NULL, SND_SYNC); //MY PROBLEM
cont = 1;
Sleep(8);
printf("\n"); //now the user should start writing his word again from the beginning
break;
}
else if (filas[maxIndex][i + 1] == '\0') {
cont = 0;
i++;
break;
}
else { cont = 0; }
i++;
}
if (cont == 0) {
userWord[i] = '\0';
if (length != length2) { //calculated before, but irrelevant to my problem
cont = 1;
Sleep(8);
printf("\n\n%s\n", filas[maxIndex]);
}
}
}
if (cont != 3) {
while (!kbhit()) {}
option = getch(); // if option = '2' the user closes the program and if it equals ' ' the next word if obtained with a function and the loop begins again.
}
}
我的問題是,如果他類型的快,因爲他想盡快結束,他會做出一個拼寫錯誤(寫入「AKBA」,而不是「阿爾巴」)和FailSound打3次。我想在做出錯誤時忽略用戶輸入的其餘部分,但我不知道如何去做。
_Note_:我可能是錯在這裏(我目前沒有一個_Win_箱進行測試),但我想你應該添加一個'睡眠(1); 'while(!kbhit())'循環中的語句,否則當用戶沒有按任何東西時,程序會殺死你的一個處理器。 – CristiFati
不幸的是,我無法將描述中的問題鏈接到提供的代碼。 1:'break'語句從__outer__循環中取出(與註釋中的內容相反)。另外'i'不會增加,所以代碼在數組的相同字符上運行。另外,如果用戶緩慢地按錯了序列,您又希望它的行爲如何? _注意:不是「試圖忘記」(無效?)字符,你可以自己丟棄它們(不要將它們放在'userWord'中) – CristiFati
我修改了代碼,希望現在你可以理解它,對於以前缺乏信息。現在,我怎麼能丟棄自己的字符?我不會提出一個想法,因爲他們就像被記住......我不知道,他們不是用戶詞的一部分,直到我到達getch(),但是這會讓他們...... @CristiFati –