2013-10-11 134 views
-2

我想一次讀取一個字符,並以累積方式將它們轉換爲int。如果用戶輸入數字以外的字符,我會重新開始整個過程​​。 當我運行此代碼時,只有在按下Enter鍵而不是每次按鍵執行後,纔會執行getchar()以下的代碼。簡而言之,不是每次只輸入一個字符,而是以一個以enter結尾的字符串作爲輸入,然後從輸入字符串中一次讀取一個字符並執行while循環。 我很確定它與printf語句中的\n有關。 我的C代碼:getchar()工作異常

char* input=malloc(0); 
    char c; 
    int count=0; 
    int a; 
    int b; 
    errno=0; 
    printf("\nEnter two numbers a and b\n"); 

    while(1){ 
     count++; 
     printf(":Count:%d",count); 
     c=getchar(); 
     printf("\n::%c::\n",c); 
     if(c=='\n') 
      break; 
     input=realloc(input,count); 
     input[count-1]=c; 
     errno=0; 
     a=strtol(input,NULL,10); 
     printf("\nNUMber::%d\n",a); 
     if (errno == ERANGE && (a == LONG_MAX || a == LONG_MIN)){ 
      printf("\nLets start over again and please try entering numbers only\n"); 
      count=0; 
      input=realloc(input,0);  
     } 
    } 
+0

這是因爲一個事實,即'的getchar()'是終端IO的設置有關。由於大多數終端都啓用了線路緩衝功能,因此它會等到您按下回車鍵。使用'termios.h',你可以禁用它。 'getch()'是僅限windows的。另外,爲什麼'realloc(,0)'?爲什麼不只是'free()'?.另外,'malloc(0)'是未定義的行爲。它可以返回NULL或SEGFAULT。 – cyphar

+0

「getch()工作異常」 - 我懷疑。一個體面的標準庫實現幾乎沒有錯誤。 – 2013-10-11 11:40:18

+0

mybad再次讀取標題..its getchar() – thunderbird

回答

1

這是因爲一個事實,即getchar()是終端IO的設置有關。由於大多數終端都啓用了線路緩衝功能,因此它會等到您按下回車鍵。使用termios.h,您可以禁用它。 getch()是僅限Windows。

下面是一些代碼來做什麼getch()在Linux中。

#include <termios.h> 

char getch(void) { 
    /* get original settings */ 
    struct termios new, old; 
    tcgetattr(0, &old); 
    new = old; 

    /* set new settings and flush out terminal */ 
    new.c_lflag &= ~ICANON; 
    tcsetattr(0, TCSAFLUSH, &new); 

    /* get char and reset terminal */ 
    char ch = getchar(); 
    tcsetattr(0, TCSAFLUSH, &old); 

    return ch; 
} 

另外,爲什麼realloc(blah, 0)?爲什麼不只是free(blah)? 另外,malloc(0)是未定義的行爲。它可以返回NULL或給出一個唯一的指針。與realloc(blah, 0)相同。

+0

http://stackoverflow.com/questions/2022335/whats-the-point-in-malloc0 – thunderbird

+0

但'免費(空)'是有效的,並允許。 – cyphar

+0

所以malloc(0)..順便說一句你的代碼工作。 – thunderbird

0

只需使用:

#include <stdlib.h> 

char getch() 
{ 
char c; // This function should return the keystroke 

system("stty raw"); // Raw input - wait for only a single keystroke 
system("stty -echo"); // Echo off 

c = getchar(); 

system("stty cooked"); // Cooked input - reset 
system("stty echo"); // Echo on - Reset 

return c; 
} 
+0

'system()'是不安全的。如果某人用一些邪惡的東西替換了「stty」二進制文件會怎麼樣?或者他們只是在當前目錄中放入一個邪惡的二進制文件,並將路徑改爲'。:/ bin:/ usr/bin'? – cyphar