开发者

C++ cin positive integers only

开发者 https://www.devze.com 2023-04-03 20:00 出处:网络
This is my first time on Stackoverflow. I was making a program to find out MPG for a car. I was wondering how can I make the cin statement only a开发者_开发百科ccept positive integers only? and also,

This is my first time on Stackoverflow. I was making a program to find out MPG for a car. I was wondering how can I make the cin statement only a开发者_开发百科ccept positive integers only? and also, if you do enter a invalid input, can you reset it? I am not sure if that makes sense. I didn't have to do this for class. I was just curious on how to do it. Here is the code.

#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;
}


iostreams are not a toolkit for building a complex UI. Unless you want to write your own rather complex stream to wrap the usual stream, there is no way you are going to get it to either (a) only accept positive integers or (b) interact politely with a user who types in something else.

You should just read lines from cin, and print your own error prompts and such after you look at what you get.


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));

If you do this after running the statements it will rerun them if the answer is 0 or lower or is not an integer. If you make the variables ints instead of doubles then you can remove the "&& ((int)miles == miles)" part of the while statement.


Still, there are a couple of standard ways to do it in a command line environment.

You could trap the cin statement in a loop that doesn't release until a valid input has been entered. This is the "standard" way to validate CLI input, not just signed numbers.

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

The condition in the while statement is the place to validate the data. You can also make an if statement to explain why the input is invalid.

The other way is to simply force the value to be positive, by simply going tank = fabs(tank);, which takes the absolute value (i.e. positive) of the tank variable.


    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!
        }
    }


Instead of

cin >> miles;

Try

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

That will repeat the question until the input is positive. You can do that for the rest of the questions too.

Note that input streams are not intended for input filtering. You have to provide your own logic for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消