2013-01-23 129 views
8

我正在嘗試爲一個類製作一個簡單的C程序,其中一個要求是我需要爲所有輸入和輸出使用scanf/printf。我的問題是爲什麼我的主循環中的scanf跳過並且程序剛剛終止。scanf正在跳過

這裏是我的代碼

#include <stdio.h> 

void main() { 
    int userValue; 
    int x; 
    char c; 

    printf("Enter a number : "); 
    scanf("%d", &userValue); 
    printf("The odd prime values are:\n"); 
    for (x = 3; x <= userValue; x = x + 2) { 
     int a; 
     a = isPrime(x); 
     if (a = 1) { 
      printf("%d is an odd prime\n", x); 
     } 
    } 
    printf("hit anything to terminate..."); 
    scanf("%c", &c);  
} 

int isPrime(int number) { 
    int i; 
    for (i = 2; i < number; i++) { 
     if (number % i == 0 && i != number) 
      return 0; 
    } 
    return 1; 
} 

我能夠通過第一個後加入另一相同scanf「修復」,但我寧願只使用一個。

+1

你試過'系統(「暫停」);'? –

+0

是直接C還是隻有C++? –

+0

Staight c。注意缺少名稱空間? –

回答

19

在前一個int被輸入後,stdin中的新行字符將不會被最後一次調用scanf()所消耗。所以在for循環之後調用scanf()會消耗換行符,並且繼續執行,而用戶不必輸入任何內容。

要糾正,而無需添加其他scanf()呼叫你可以在for循環後使用格式說明" %c"scanf()。這將使scanf()跳過任何前導空格字符(包括換行符)。請注意,這意味着用戶必須輸入除換行符以外的內容才能結束程序。

此外:

  • 檢查scanf()結果,以確保它實際上分配一個值傳遞的變量:

    /* scanf() returns number of assigments made. */ 
    if (scanf("%d", &userValue) == 1) 
    
  • 這是一個任務(而且將永遠是真實的) :

    if (a = 1){ /* Use == for equality check. 
           Note 'a' could be removed entirely and 
           replace with: if (isPrime(x)) */ 
    
+1

爲什麼最後一次調用'scanf()'沒有被佔用?抱歉,新問題 –

+2

@SSHThis,'scanf(「%d」)'在遇到非數字的東西時停止使用,而換行符不是數字,因此它將保留。 – hmjd

+0

感謝您收集錯誤 –