2016-03-12 20 views
0
printf("please enter a value for side a: "); 
check1 = scanf(" %d*%c", &a); 
while(check1 != 1) 
    { 
    printf("You have entered an invalid value"); 
    scanf(" %d*%c", &a); 
    } 
printf("The value for A is: %d\n", a); 

我想,以確保輸入的值只對一個整數(CHECK1!= 1)。如果我輸入除整數之外的任何東西並且while循環參與,它將無限打印「您輸入的值無效」,但忽略scanf以重新輸入A的值。如何重新在一個「而」循環進入一個整數值?

我在此之前編寫了一段代碼這並沒有(檢查!= 1)的一部分,但有while循環工作內scanf函數。

printf("\nEnter the denominator number: "); 
scanf("%d%*c", &num2); 
while (num2 <= 0) 
    { 
    printf("The denominator can not be 0 or less, re enter the number: "); 
    scanf("%d%*c", &num2); 
    } 

注意這第二塊代碼的作品。

我該如何解決這個問題?或者有人能提出一個簡單的替代確保「一」是一個整數?我很新的編程和scanf是唯一的輸入提示我所知道的。

幫助,將不勝感激:)

回答

0

裏面你需要使用「scanf函數」功能後更改「CHECK1」的值while循環。

int a; char* w; 
printf("please enter a value for side a: "); 
int check1 = scanf(" %d*%c", &a); 
while (check1 != 1) 
{ 
    scanf("%s", &w); 
    printf("You have entered an invalid value\nplease enter a value for side a: "); 
    check1 = scanf(" %d*%c", &a); 
} 
printf("The value for A is: %d\n", a); 
+0

修改我什麼價值?我試着在while循環內執行「check1 = scanf(」%d *%c「,&a);」)無效 - 關於代碼的問題! – Josh

+0

@Josh,請不要在代碼中張貼代碼,它是不可讀的。 –

+0

謝謝你,這正是我需要的! – Josh

相關問題