我想一次讀取一個字符,並以累積方式將它們轉換爲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);
}
}
這是因爲一個事實,即'的getchar()'是終端IO的設置有關。由於大多數終端都啓用了線路緩衝功能,因此它會等到您按下回車鍵。使用'termios.h',你可以禁用它。 'getch()'是僅限windows的。另外,爲什麼'realloc(,0)'?爲什麼不只是'free()'?.另外,'malloc(0)'是未定義的行爲。它可以返回NULL或SEGFAULT。 –
cyphar
「getch()工作異常」 - 我懷疑。一個體面的標準庫實現幾乎沒有錯誤。 – 2013-10-11 11:40:18
mybad再次讀取標題..its getchar() – thunderbird