2016-12-29 39 views
0

我有一個項目爲學校和它,我需要得到一個四位數字,然後用無輸入立即繼續。例如:「輸入一個數字:1424」,然後它只是繼續,並且你不能再輸入數字,因爲不需要按Enter鍵。 我試過scanf("%4d",&num);,但它等待Enter鍵。Ç - 如何突破scanf函數,沒有進入並沒有字符串

還有一限制是...我不能在這個項目中使用字符串,因此所有的解決方案必須是不附帶任何條件。

+1

歡迎來到Stack Overflow!請說明迄今爲止的研究/調試工作。請先閱讀[問]頁面。 –

+0

要實現此功能,您需要[ncurses](https://en.wikipedia.org/wiki/Ncurses)。 – emlai

+3

您尋求的行爲由* terminal *控制,而不是由您的程序控制。 'scanf'不能阻止你的終端接受來自用戶的更多字符。在用戶按下輸入之後,它不會「重新獲得控制權」。爲此,你需要一個像ncurses這樣的終端訪問庫。 –

回答

0

組織輸入而不輸入按鍵的唯一途徑是功能getchgetcheconio.h頭,即我想是不是在C/C++標準。所以POSIX標準名稱是_getch_getche

有了這功能,你會讀出字 - 如果你單獨處理每個char這不是字符串。

UPDATE:

我的解決辦法是:

#include <stdio.h> 
#include <ctype.h> 
#include <conio.h> 

int main(void) 
{ 
    char ch; // to store an input - single char 
    int number = 0; // to make number from inputs 
    printf("Enter a number: "); 
    int digits_cnt = 0; 
    while (digits_cnt < 4) 
    { 
     ch = _getche(); 
     if (isdigit(ch)) 
     { 
      number *= 10; // add an order to number 
      number += ch - '0'; // add a decimal digit to number 
      digits_cnt++; // count this digit to stop loop 
     } 
    } 
    // just to check result 
    printf("\nThe number %d was entered.\n", number); 
    return 0; 
} 

我認爲所有的4位數字應該成爲一個數,但是,也許,你需要做別的事情與他們。

+0

這是完美的!非常感謝你! –

0

對於讀4個位數你可能想使用char * fgets (char * str, int num, FILE * stream);,會做你要求什麼了。你不應該使用scanf進行交互式輸入,你可以找到爲什麼在這個article

因爲你在ascii中輸入輸入的字符串部分,你已經在使用字符串(字符數組)。