2015-10-16 34 views
0

初學者在這裏。我試圖讓用戶輸入一個正數。然而while循環似乎並不適用於用戶輸入時數字不正確的情況。C編程。試圖循環捕捉用戶輸入正數

輸出:

Please enter a positive integer: -3 
I'm sorry, you must enter a positive integer greater than zero: why? 
I'm sorry, you must enter a positive integer greater than zero: -42 
I'm sorry, you must enter a positive integer greater than zero: 42 
The positive integer was : 42 
Press any key to continue.... 

代碼:

#define _CRT_SECURE_NO_WARNINGS 
#include<stdio.h> 
void clear_keyboard_buffer(void); 
int main() 
{ 
    int k; 
    printf("Please enter a positive integer: "); 
    scanf("%d", &k); 
    if (k > 0) 
    { 
     clear_keyboard_buffer(); 
     printf("The positive integer was: %d ", k); 

    } 
    while (k<=0) 
    { 
     printf("I'm sorry, you must enter a positive integer greater than zero: "); 
     scanf("%d", &k); 
     return 0; 
    } 
} 

void clear_keyboard_buffer(void) 
{ 
    char ch; 
    scanf("%c", &ch); 
    while (ch != '\n') 
    { 
     scanf("%c", &ch); 
    } 
} 
+0

你可以嘗試做一個else語句爲您如果(K > 0),然後把你的時間塊在那裏。 – CurseStacker

+0

@CurseStacker這樣別人 \t { \t \t而(K <= 0) \t \t { \t \t \t的printf( 「對不起,你必須輸入一個正整數大於零」)?; \t \t \t的scanf( 「%d」,&k); \t \t \t返回0; \t \t} \t} – hfu0823

+0

代碼不匹配 「輸出:」 從while循環 – chux

回答

1

好吧,我認爲這是最簡單的向你展示一些代碼,你想要做什麼,與你爲什麼應該做一些評論沿它那樣:

#include <stdio.h> 

int main(void) /* note the void here, it says "no parameters"! */ 
{ 
    int k; 

    /* here we don't use printf() because there is no formatting to do */ 
    fputs("Please enter a positive integer: ", stdout); 

    scanf(" %d", &k); /* note the space, it consumes any whitespace */ 

    while (k < 1) 
    { 
     fputs("I'm sorry, you must enter a positive integer greater " 
       "than zero: ", stdout); 
     scanf(" %d", &k); 
    } 

    printf("You entered `%d'\n", k); 

    return 0; 
} 

還有你應該檢查產品質量代碼的返回值scanf(),因爲可能是錯誤(例如,用戶在輸入的東西是不是數字...)

話雖這麼說,對於真正可靠用戶輸入,我建議乾脆放棄scanf(),只是使用如fgets()閱讀一行輸入(任何),然後解析自己。 strtol()可以來得心應手......

只給你一個想法是什麼,我說什麼,這裏有一個非常簡單的,但可靠的解決方案:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

static int readInt(void) 
{ 
    char buf[1024]; 
    int input; 
    char *endptr; 

    fgets(buf, 1024, stdin); 

    /* strip off "end of line" characters */ 
    buf[strcspn(buf, "\r\n")] = 0; 

    input = strtol(buf, &endptr, 10); 

    /* sanity check, only accept inputs that can be wholly parsed as 
    * an integer 
    */ 
    if (buf[0] == 0 || *endptr != 0) input = -1; 

    return input; 
} 

int main(void) 
{ 
    int k; 

    fputs("Please enter a positive integer: ", stdout); 

    k = readInt(); 

    while (k < 1) 
    { 
     fputs("I'm sorry, you must enter a positive integer greater " 
       "than zero: ", stdout); 
     k = readInt(); 
    } 

    printf("You entered `%d'\n", k); 

    return 0; 
}