2011-09-08 8 views
3

これは私の初めてのStackoverflowです。 私は車のMPGを見つけるプログラムを作っていました。私はcin文が正の整数だけを受け入れるようにするにはどうすればいいでしょうか?また、無効な入力を入力した場合は、リセットすることはできますか?それが意味をなさないかどうかはわかりません。私はクラスのためにこれを行う必要はなかった。私はちょうどそれをする方法に興味があった。ここにコードがあります。C++のシンプルな整数のみ

#include <iostream> 
using namespace std; 

int main() 
{ 
double tank, miles, mpg; 

cout << "Hello. This is a program that calculates the MPG (Miles Per Gallon) for  your\n" ; 
cout << "vehicle\n" << endl; 
cout << "Please enter how many gallons your vehicle can hold\n" << endl; 
cin >> tank; 
cout << endl; 
cout << "Please enter how many miles that have been driven on a full tank\n" <<endl; 
cin >> miles; 
cout << endl; 

mpg = (miles)/(tank); 
cout << "Your vehicle recieves " << mpg << " miles per gallon\n" << endl; 
system ("pause"); 
return 0; 
} 
+3

あなたの質問には答えられませんが、整数を必要とする場合はダブルスを求めてはいけません。 –

+0

最初に整数を求めてから、それが正ではないという事実を扱います。さらに文字列を読んで構文解析して、それが必要なものであることを確認します。誰かが必要としないものを入力し、別の機会を与えた場合、エラーを報告します。 –

+0

これでキーボードから物理的にキーを削除することはできません。人々は入力ミスをするでしょう。 – MSalters

答えて

4

iostreamsは複雑なUIを構築するためのツールキットではありません。通常のストリームをラップするために独自のストリームを作成したい場合を除いて、(a)正の整数のみを受け入れるか、(b)他のタイプを入力するユーザーと丁寧にやりとりすることはできません。

ちょうどcinから行を読み、あなたが得るものを見た後にあなた自身のエラープロンプトなどを出力する必要があります。

+0

私は最後の文章が正確に質問をしていると思います。彼は空想的なことを求めていない。 – Potatoswatter

-3

代わりの

cin >> miles; 

は、入力が正まで質問を繰り返すことになります

while ((cin >> miles) < 0) 
cout << "Please enter how many gallons your vehicle can hold\n" << endl; 

を試してみてください。あなたは残りの質問についてもそれを行うことができます。

入力ストリームは入力フィルタリング用ではありません。あなたはそれのための独自のロジックを提供する必要があります。

+6

'cin >> miles'という式は' cin'を返しますので、どのように動作するはずです。 – user786653

+0

これは、非数値出力のエラー・チェックも行いません。 –

1
cout << "Hello. This is a program that calculates the MPG (Miles Per Gallon) for  your\n" ; 
cout << "vehicle\n" << endl; 
do 
{ 
    cout << "Please enter how many gallons your vehicle can hold\n" << endl; 
    cin >> tank; 
    cout << endl; 
} while (tank <= 0 && ((int)tank != tank)); 
do 
{ 
    cout << "Please enter how many miles that have been driven on a full tank\n" <<endl; 
    cin >> miles; 
    cout << endl; 
} while (miles <= 0 && ((int)miles != miles)); 

この文を実行した後で、答えが0以下または整数でない場合は、文を実行した後に再実行します。変数をdouble型ではなくints型にすると、whileステートメントの "& &((int)miles == miles)"部分を削除することができます。

+0

私はあなたが私が何を意味するのか理解していますが、コードに入れても、同じことを常に繰り返しています。あなたの車が保持できるガロン数を入力してください。そして私はそれをintに変更し、倍にしませんでした。 – Sujay

+0

ああ、私!私は意味するときに==をタイプしたようです!= これでうまくいくはずの投稿を編集しました – annirun

0

まだ、コマンドライン環境で標準的な方法を実行する方法がいくつかあります。

有効な入力が入力されるまで、解放しないループでcin文をトラップすることができます。これは、符号付きの数値だけでなく、CLI入力を検証するための「標準的な」方法です。

do 
{ 
    cout << "\nPlease enter..."; 
    cin >> tank; 
} 
while (tank < 0) 

while文の条件は、データを検証する場所です。 if文を使用して、入力が無効な理由を説明することもできます。

もう1つの方法は、tank変数の絶対値(つまり正数)を取るだけで、tank = fabs(tank);に行くだけで、値を正の値にすることです。

+2

これは、例えば文字が入力されると、無限ループに入ります。 – Potatoswatter

+0

実際には、 'tank'は初めに初期化されていないため、条件に最初に到達するまでに初期化されることは保証されていないため、未定義の動作です。 –

+0

本当ですか? Potatoswatterは、手紙が入力された場合、条件を誤っているとみなしてループして新しいcinを行うべきではないでしょうか? Karl:タンクは初期化できません。これはパスが最初にcinを通過するためです。それはdoのメリットです... whileの代わりに。 –

0
So this is my code for an infinite loop 
    1: So main will call the "Get_number()" function 
    2: Get number will accept an int from the user 
    3(A): If int is greater than 0, go into loop 
    3(B): Else, display to user "Invalid Input" and then call the function 
      "Get_number()" again creating an infinite loop until the user 
      enters a value greater than 0 



    #include <iostream> // Access the input output stream library 
    #include <fstream> // Access to the fstream library (used to read and write to files) 
    #include <chrono> // Needed to access "std::chrono_literals" 
    #include <thread> // Needed to access "namespace std::this_thread" 

    using std::fstream; // this will allow us to use the fstream (we'll be able to read and write to files) 
    using std::ios;  // needed for iostream (used to be able to tell fstream to read and/or write to a file and that it's reading/writing a binary file) 
    using std::cout; // need this statment to access cout (to display info to user) 
    using std::cin;  // need this statment to access cin (to gather info from user) 
    using std::endl; // need this statment to access endl (will end the line) 
    using namespace std::this_thread; // This will allow me to use "Sleep_For" or "Sleep_Until" 
    using namespace std::chrono_literals; // This will allow the use of measurements of time such as ns, us, s, h, etc. 

    //Prototypes*************************************************************************************************** 
    void shellSort(int read[], int readLength); //Making Prototype (Declaring our function) so that compiler knows not to worry about it 
    void Get_number(); 
    void Write_to_file(int user_input_of_how_many_random_numbers_to_generate); //Making Prototype (Declaring our function) so that compiler knows not to worry about it 
    void Read_from_file(int user_input_of_how_many_random_numbers_to_generate);//Making Prototype (Declaring our function) so that compiler knows not to worry about it 
    //************************************************************************************************************* 

    void main() 
    { 
     Get_number(); 

     system("pause>>void"); // will let the console pause untill user presses any button to continue 

    } 

    /************************************************************************************************************** 
    * Purpose: This function will gather a positive integer from the user and use it to generate that many 
    *   random numbers! 
    * 
    * Precondition: None 
    * 
    * 
    * Postcondition: 
    *   Would've gathered the number of random numbers the user wanted to generate and then gone into the 
    *   Write_to_file and Read_from_file function 
    * 
    **************************************************************************************************************/ 

    void Get_number() 
    { 
     int user_input_of_how_many_random_numbers_to_generate = 0; //make variable that will accept the int value the user wants to generate random numbers 
     cout << "Please Enter A Number Greater Than Zero:" << endl; // displays to user to enter a number greater than zero 
     cin >> user_input_of_how_many_random_numbers_to_generate; // will accept the value the user inputted and place it in the "user_input_of_how_many_random_numbers_to_generate" variable 
     system("cls"); // Will clear the screen 
     if (user_input_of_how_many_random_numbers_to_generate > 0) // if user input is greater than zero, enter this 
     { 

      Write_to_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Write_to_file" function 
      Read_from_file(user_input_of_how_many_random_numbers_to_generate); // will bring up the "Read_from_file" function 
     } 
     else // else enter this 
     { 
      cout << "invalid input!" << endl; // display to user "invalid input" 
      sleep_for(2s); // system will pause for 2 seconds allowing the user to read the message of "invalid input" 
      system("cls"); // console will be cleared 
      Get_number(); // Get_number function will be entered creating an infinate loop untill the user's input is valid! 
     } 
    } 
関連する問題