我正在爲一個大學作業開發一個小型C程序,並且我注意到了我的代碼中存在一個奇怪的錯誤。我一般使用帶有短鍵盤的iMac,但是它的電池很平坦,所以我插入了帶數字鍵盤的標準USB鍵盤。數字鍵盤[Enter]不是 n在C?
奇怪的是,如果我按[Enter]在我的數字鍵盤,它似乎做定期回車}鍵做什麼,但\ n我想在我提出的標準輸入功能檢測閱讀鍵盤輸入時,在使用數字鍵盤的[Enter]鍵時不起作用。
Wtf?
這是我的功能,讀取用戶輸入:
/* This is my implementation of a stdin "scanner" function which reads
* on a per character basis until the the termination signals are found
* and indescriminately discarding all characters in the input in excess
* of the supplied (limit) parameter. Eliminates the problem of 'left-over'
* characters 'polluting' future stdin reads.
*/
int readStdin(int limit, char *buffer)
{
char c;
int i = 0;
int read = FALSE;
while ((c = myfgetc(stdin)) != '\n' && c != '\0') {
/* if the input string buffer has already reached it maximum
limit, then abandon any other excess characters. */
if (i <= limit) {
*(buffer + i) = c;
i++;
read = TRUE;
}
}
/* clear the remaining elements of the input buffer with a null character. */
for (i = i; i < strlen(buffer); i++) {
*(buffer + i) = '\0';
}
return read;
}
/* This function used to wrap the standard fgetc so that I can inject programmable
* values into the stream to test my readStdin functions.
*/
int myfgetc (FILE *fin) {
if (fakeStdIn == NULL || *fakeStdIn == '\0')
return fgetc (fin);
return *fakeStdIn++;
}
NB:本myfgetc
和隨後*fakeStdIn
是的方式,我可以單元測試我的代碼和「注入」項目到STDIN流部在編程上像某人在這個問題上提出的建議:How do I write a testing function for another function that uses stdin input?。
爲什麼不添加一個調試printf語句來查看該字符是什麼?我的猜測是它是0x03。 – 2011-05-22 21:59:20
請注意,你的'for'循環清除你的緩衝區非常尷尬; 'i = i'值得一笑(你可以留下任何表達式空白:'for(;;)'是無限循環的有效語法)但是'i
sarnold
2011-05-22 22:18:22
所以我做到了這一點,事實證明沒有數字鍵盤鍵實際上進入標準輸入流。他們在控制檯中工作,但是當我將數字鍵盤和非數字鍵盤字符混合在一起時,只有非數字鍵盤字符出現在char *中。 – Ash 2011-05-22 22:19:51