2014-04-15 15 views
0

首先,我對c完全不熟悉。如果你像對待我一樣的初學者,那就太好了。是否可以使用scanf(「%d」&i)並僅使用第一個輸入的數字,而沒有別的?

所以,我的問題是,我似乎無法做到這一點,使程序只接受一個數字的信息,使用它,然後忽視任何其他信息。

目前,我有一些與此類似:

#include <stdio.h> 
#include <string.h> 
int main(){ 
    int i, ret; 
    char c, type; 
    do 
    { 
     printf("Convert ASCII # to character\n"); 
     printf("q: Quit.\n"); 
     scanf("%c", &type); 
/* I use the " if(type== 'n'); " a number of times. */ 
/* I left the others out to simplify what my problem is. */ 
     if(type=='1'){ 
      printf("ASCII NUMBER -> CHAR \n"); 
      printf("\t Please input one ASCII code \n"); 
      int ret = scanf("%d", &i); 
/* My aim here is to get the amount of integers the user inputs,*/ 
/* and use that to categorize, but I think I am failing to do so. */ 
      if(ret==1){ 
       printf("\t The character for ASCII code %d is -> '%c' \n\n", i, i); 
       break; 
      } 
      else{ 
       printf("Please input one number./n/n"); 
       break; 
      } 
     } 

    } 
    while(type=='q'); 
    return 0; 
/* A problem I face a lot is where the program would terminate*/ 
/* even when the while conditions weren't met. */ 
} 

我希望你能明白我想通過看上面的代碼做。
任何幫助將不勝感激!

回答

1

由於輸入緩衝區中留有字符[enter],程序結束。
您爲類型輸入值,然後按[Enter]。這個[enter]是一個留在輸入緩衝器中的字符,將被下一個讀取

scanf("%c",type); 

所以循環退出。因此使用getchar()

int ret = scanf("%d", &i); 

要清除輸入緩衝區。並且循環不會意外結束。
進行這些更改,

printf("\t Please input one ASCII code \n"); 
      int ret = scanf("%d", &i); 
      getchar();   //this will read the [enter] character in input buffer 
/* My aim here is to get the amount of integers the user inputs,*/ 
/* and use that to categorize, but I think I am failing to do so. */ 
      if(ret==1){ 
+0

對不起,我不是太熟悉使用的getchar()。我該怎麼做才能保持循環,並且沒有在輸入緩衝區中留下回車鍵? – user3536816

+0

@ user3536816使用scanf()讀取整數後,'\ n'將留在輸入緩衝區中。所以只需添加一個'getchar()'語句並嘗試執行程序。 – LearningC

1

在一般情況下,我覺得它更好地使用fgets()(或者,如果使用的是C99,gets_s() - 雖然我還是喜歡與fgets()最大的可移植性年長編譯環境)對於所有基於用戶的輸入,則必要時使用sscanf(),strtol()等將字符串轉換爲其他數據類型,因爲這樣可以按緩衝區安全的方式逐行讀取數據,您不必擔心關於輸入緩衝區中剩下的東西。這對於基於用戶的輸入尤其如此,因爲這種輸入永遠不會形成良好(由於拼寫錯誤等原因)。 scanf()在從格式正確的輸入文件中讀取時確實非常有效。

見comp.lang.c常見問題,從中介紹了一些詳細使用scanf()時,包括你在上面看到的問題,在這裏輸入似乎越來越頻繁發生的問題跳過:

要了解有關任何C標準庫函數的更多信息,請在Linux命令提示符(或Google)中輸入:man 3 fgets等等。

例子:

char buffer[256], type; 
fgets(buffer, sizeof(buffer), stdin); 
if(sscanf(buffer, "%c", &type) == 1) { 
    // Was able to read a char from the buffer, now you can use it. 
} 
else { 
    // Wasn't able to read a char from the buffer. handle it if required. 
} 
+0

感謝您的信息!但是,我不知道sscanf()和strtol()是做什麼的。我想我還有很長的路要走:s。 – user3536816

+0

增加了用於在C標準API中查找文檔的示例和'howto'。 – JohnH

+0

+1 for'fgets()' – chux

相關問題