2011-05-22 77 views
4

我正在爲一個大學作業開發一個小型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?

+0

爲什麼不添加一個調試printf語句來查看該字符是什麼?我的猜測是它是0x03。 – 2011-05-22 21:59:20

+0

請注意,你的'for'循環清除你的緩衝區非常尷尬; 'i = i'值得一笑(你可以留下任何表達式空白:'for(;;)'是無限循環的有效語法)但是'i sarnold 2011-05-22 22:18:22

+0

所以我做到了這一點,事實證明沒有數字鍵盤鍵實際上進入標準輸入流。他們在控制檯中工作,但是當我將數字鍵盤和非數字鍵盤字符混合在一起時,只有非數字鍵盤字符出現在char *中。 – Ash 2011-05-22 22:19:51

回答

0

所以事實證明,這是一個Mac OSX的東西。我已經與其他Mac用戶交談過,他們也遇到了同樣的問題。從來沒有找到修復,因爲可能根本就不存在。這個問題在Solaris機器上不會發生,因爲這是代碼將運行的操作系統,我想這並不重要。

我將自己回答這個問題,答案是它只是那些OSX「怪癖」中的一個而已。

1

你爲這個小測試得到了什麼輸出?

#include <stdio.h> 
int main(int argc, char* argv[]) { 
    int c; 
    while((c=getchar()) != EOF) { 
     printf("%d\n", c); 
    } 
    return 0; 
} 
+0

它沒有輸出任何東西(每當我點擊數字鍵盤上的回車鍵時,只需要換一行)。當我點擊常規輸入鍵時輸出「10」。 – Ash 2011-05-22 22:39:14

+0

我的普通Mac鍵盤有扁平電池,而我使用的USB鍵盤沒有功能鍵。 – Ash 2011-05-22 22:55:23

+0

Doh!愚蠢的我,你在你的問題的第一句中解釋過!我刪除了我的愚蠢評論,以免混淆他人! – 2011-05-22 23:00:11

0

完全可以在Mac,你得到\r\n,不只是\n

相關問題