2016-03-26 7 views
1

私は、ユーザーが特定の条件の変数を後の計算で使用するために入力するようにしようとしています。つまり、vmaxを超えることはできません。ゼロより小さくなく、文字列ではありません。do while条件発行

これは私が持っているものです。

do 
    { 
     scanf("%f", &vkmh); 
     if (vkmh <= vmax) 
     { 
     }   
     else if (vkmh < 0) 
     { 
      printf("Error, speed must be positive.\n"); 
     } 
     else if (vkmh > vmax) 
     { 
      printf("Error, the max speed of this vehicle is listed as %.fkm/h.\nIt cannot exceed that value. Please enter a value under %.f.\n", vmax, vmax); 
     } 
     else if (vkm != getchar()) 
     { 
      printf("Error in input. Please only use numbers\n"); 
     } 
    } 
    while(vkmh > vmax || vkmh < 0 || vkm != getchar()); 

理論的に有効な値は有効な応答を返し、vmaxを超える値は無効な応答を返し、ユーザーに再入力を要求します。しかし、負または文字列は何も返しません。

どのように私はこれを動作させることができますか?

+0

ジャスト予告:答えはこの回答のそれに非常に似ていることに注意してください。 'vmax> = 0'のとき' if(vkmh <= vmax){X} else if(vkmh <0){Y} 'はブランチ' Y'を実行しません。 – Marian

+0

どうすればこれらの条件に対して別々の操作を行うことができますか? –

+0

あなたは一度に一つのことをするという概念について聞いたことがありますか? –

答えて

2

あなたは何を達成するために以下のコードを使用することができます探しています。

How to scanf only integer and repeat reading if the user enter non numeric characters?

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

int clean_stdin() 
{ 
    while (getchar()!='\n'); 
    return 1; 
} 

int main() 
{ 
    float vkmh, vmax = 100.0; 

    setbuf(stdout, NULL); 

    vkmh = vmax + 1.0; /* value to start the loop */ 
    while (vkmh < 0 || vkmh > vmax) { 
     printf("Please enter value for the velocity in km/h: "); 
     if (scanf("%f",&vkmh) == 1) { 
      if (vkmh < 0) { 
       /* This was your 2nd if condition, but would never have executed assuming that vmax > 0. */ 
       printf("Error, speed must be positive.\n"); 
       exit(1); 
      } else if (vkmh <= vmax) { 
       /* Do something */ 
      } else { 
       /* No need for the else if, this is the only other possibility */ 
       printf("Error, the max speed of this vehicle is listed as %.fkm/h.\n" 
         "It cannot exceed that value. Please enter a value under %.f.\n", vmax, vmax); 
      } 
     } else { 
      printf("Error in input.\n"); 
      clean_stdin(); 
     } 
    } 
    printf("\nValue read: %f km/h\n",vkmh); 
    return 0; 
} 
0

まずはC#ではなくCです。 getchar標準入力から読み込むので、getchar()を3回呼び出すと最大3回のユーザー入力を読み込みます。だからあなたはそれらの通話を削除することができます。

scanf関数は、成功したコンバージョンの数を返します。したがって、ユーザーはこれを使用して(== 1)、正しいフロート値を入力していないかどうかを確認できます。

編集:私は、私は自分の携帯電話上でコンパイルできないようなコードを削除した、このページのatof例のように申し訳ありません 使用するfgets/http://www.cplusplus.com/reference/cstdlib/atof/

+2

その構造体は数字に対しては問題なく動作しますが、文字列をうまく処理できません。 "K"のようなものを入力すると、 "Error in input"メッセージが無限に繰り返されます –

+0

申し訳ありませんが、状態変数を忘れました。 –

+0

入力した文字を消費するために 'scanf("%c "、&c);'内部で 'scanf("%f "、&vkmh)!= 1)'を追加してください。 –