getline(cin, name) causes seemingly never-ending prompt for input - c++

I'm writing a program that needs to read user input into a string object. I'm using getline(cin, name), but when it gets to the prompt, I can type anything in and press enter, but it'll just go to the next line and the cursor will keep blinking, prompting for more input. Essentially, the prompt for input never seems to end, no matter how many characters I type or how many times I press enter. I don't even know if it's actually sending the input into the string object. What could be causing this?
This is the entirety of the main function so far (it's not complete, the switch-case will eventually have 6 options, but it compiles without error) The relevant section begins at switch case 1:
#include <string>
#include <array>
#include <iostream>
#include "stdlib.h"
#include "Bank.h" //My own class. There is also a Bank.cpp, but I won't include the code in these unless they're deemed relevant
using namespace std;
void displayAccountInfo(); //will retrieve info on bank object
void main()
{
int accsCreated = 0; //Keeps track of how many accounts have been created so far. Allows placement of pointer to new bank object at an empty array index.
int option = 0; //Stores the option chosen by the user. Used in switch-case. Also ends do-while loop when ==6.
Bank* accounts[10]; //Will hold pointers to each bank object created by user in sequential order. No more than 10 accounts will ever be created.
Bank* accpntr; //Will point to one of the Bank objects. Used to initialize a pointer to the object in the accounts[] array.
//begin Menu prompt
do
{
cout << "[1] Create Bank object with values for accountNumber, name, and balance." << endl;
cout << "[2] Create Bank object with no parameters." << endl;
cout << "[6] End program" << endl;
cin >> option;
//begin option branch:
switch (option)
{
case 1:
{
int num; //holds account number
string name; //will hold account name as string object for use in Bank constructor
double balance; //holds account balance
cout << endl << "Enter an account number: ";
cin >> num;
cout << endl << "Enter a name for the account: ";
cin.ignore(std::numeric_limits<std::streamsize>::max()); //clears cin's buffer so getline() does not get skipped
getline(cin,name);
cout << endl << "Enter the balance of the account: ";
cin >> balance;
cout << endl;
accpntr = new Bank(num, name, balance); //creates a new bank object with attributes and a reference to it
accounts[accsCreated] = accpntr; //adds pointer to new bank object to first empty spot in array
accsCreated++; //increments total of how many bank objects have been created/what index position of accounts[] to create the next one at
} break; //end case 1
case 2:
{
accpntr = new Bank(); //creates a new bank object with an accountNumber of 9999, an empty name attribute, and a balance value of zero.
accounts[accsCreated] = accpntr; //adds pointer to new bank object to first empty spot in array
accsCreated++; //increments total of how many bank objects have been created/what index position of accounts[] to create the next one at
} break; //end case 2
case 6:
{
cout << "Ending Program." << endl;
}
} //end switch-case block
}
while (option != 6); //end menu prompt when user chooses option 6.
//end menu block
} //end function main()

The first problem is here:
cin.ignore(std::numeric_limits<std::streamsize>::max());
istream::ignore behaves like other input functions. If there's no input in the buffer, it'll block and wait until it's avaliable. It'll stop once it ignores as many characters as you told it to, or once it reaches the delimiter character (the second parameter, which you didn't specify and it defaults to traits::eof). You never even reach getline call.
To fix it, specify the delimiter:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

With alternating prompts and inputs, which impregnates a line structure on your input, you should stick to line-oriented input and read everything as a line, and use operations that convert numeric values from strings whenever appropriate.
This should be more robust than juggling with line delimiters.

Related

Infinite loop created when inputting "yy" into a char variable that should only take a single character such as 'y' or 'n', "nn" does not break code

The code in the cont function asks the user if they want to play my game again.
The code works when receiving proper character inputs such as 'y' or 'n' as well as their respective capital letter variants, and the else block works properly to loop the function if an invalid input such as 'a' or 'c' is entered.
However during a test run, an input of 'yy' breaks the code causing the program to infinitely loop, running not only this cont function but my game function as well.
choice is stored as a char variable. I am wondering why the code even continues to run upon inputting multi-character inputs such as 'yy' or 'yes'. What's interesting is 'nn', 'ny' and other variations of multi-character inputs that begin with 'n' causes no issues and properly results in the else if block running as intended. Which prints "Thanks for playing." then ends the program.
Can variables declared as char accept inputs greater than 1 character? Does it only take the first value? And if so why does 'yy' cause a loop rather than the program running as intended by accepting a value of 'y' or 'Y'? How can I change my program so that an input of 'yy' no longer causes issues, without specific lines targeting inputs such as 'yy' or 'yes'.
#include <iostream>
#include <string> // needed to use strings
#include <cstdlib> // needed to use random numbers
#include <ctime>
using namespace std;
// declaring functions
void cont();
void game();
void diceRoll();
// variable declaration
string playerName;
int balance; // stores player's balance
int bettingAmount; // amount being bet, input by player
int guess; // users input for guess
int dice; // stores the random number
char choice;
// main functions
int main()
{
srand(time(0)); // seeds the random number, generates random number
cout << "\n\t\t-=-=-= Dice Roll Game =-=-=-\n";
cout << "\n\nWhat's your name?\n";
getline(cin, playerName);
cout << "\nEnter your starting balance to play with : $";
cin >> balance;
game();
cont();
}
// function declaration
void cont()
{
cin >> choice;
if(choice == 'Y' || choice == 'y')
{
cout << "\n\n";
game();
}
else if (choice == 'N' || choice == 'n')
{
cout << "\n\nThanks for playing.";
}
else
{
cout << "\n\nInvalid input, please type 'y' or 'n'";
cont(); // calls itself (recursive function!!!)
}
}
void game()
{
do
{
cout << "\nYour current balance is $ " << balance << "\n";
cout << "Hey, " << playerName << ", enter amount to bet : $";
cin >> bettingAmount;
if(bettingAmount > balance)
cout << "\nBetting balance can't be more than current balance!\n" << "\nRe-enter bet\n";
} while(bettingAmount > balance);
// Get player's numbers
do
{
cout << "\nA dice will be rolled, guess the side facing up, any number between 1 and 6 : \n";
cin >> guess;
if(guess <= 0 || guess > 6 )
{
cout << "\nYour guess should be between 1 and 6\n" << "Re-enter guess:\n";
}
} while(guess <= 0 || guess > 6);
dice = rand() % 6+1;
diceRoll();
if (dice == guess)
{
cout << "\n\nYou guessed correctly! You won $" << (bettingAmount * 6);
balance = balance + (bettingAmount * 6);
}
else
{
cout << "\n\nYou guessed wrong. You lost $" << bettingAmount << "\n";
balance = balance - bettingAmount;
}
cout << "\n" << playerName << ", you now have a balance of $" << balance << "\n";
if (balance == 0)
{
cout << "You're out of money, game over";
}
cout << "\nDo you want to play again? type y or n : \n";
cont();
}
void diceRoll()
{
cout << "The winning number is " << dice << "\n";
}
Does it only take the first value?
Yes, the >> formatted extraction operator, when called for a single char value, will read the first non-whitespace character, and stop. Everything after it remains unread.
why does 'yy' cause a loop
Because the first "y" gets read, for the reasons explained above. The second "y" remains unread.
This is a very common mistake and a misconception about what >> does. It does not read an entire line of typed input. It only reads a single value after skipping any whitespace that precedes it.
Your program stops until an entire line of input gets typed, followed by Enter, but that's not what >> reads. It only reads what it's asked to read, and everything else that gets typed in remains unread.
So the program continues to execute, until it reaches this part:
cin >> bettingAmount;
At this point the next unread character in the input is y. The >> formatted extraction operator, for an int value like this bettingAmount, requires numerical input (following optional whitespace). But the next character is not numerical. It's the character y.
This results in the formatted >> extraction operator failing. Nothing gets read into bettingAmount. It remains completely unaltered by the >> operator. Because it is declared in global scope it was zero-initialized. So it remains 0.
In addition to the >> extraction operator failing, as part of it failing it sets the input stream to a failed state. When an input stream is in a failed state all subsequent input operation automatically fail without doing anything. And that's why your program ends up in an infinite loop.
Although there is a way to clear the input stream from its failed state this is a clumsy approach. The clean solution is to fix the code that reads input.
If your intent is to stop the program and enter something followed by Enter then that's what std::getline is for. The shown program uses it to read some of its initial input.
The path of least resistance is to simply use std::getline to read all input. Instead of using >> to read a single character use std::getline to read the next line of typed in input, into a std::string, then check the the string's first character and see what it is. Problem solved.
cin >> bettingAmount;
And you want to do the same thing here. Otherwise you'll just run into the same problem: mistyped input will result in a failed input operation, and a major headache.
Why do you need this headache? Just use std::getline to read text into a std::string, construct a std::istringstream from it, then use >> on the std::istringstream, and check its return value to determine whether it failed, or not. That's a simple way to check for invalid input, and if something other than numeric input was typed in here, you have complete freedom on how to handle bad typed in input.

Program outputs incorrect numbers from array

Jeopardy point adding code.
The program is supposed to get the number of players with a dynamic array.
From there, you can enter players names and it will insert the names into a two-dimensional array.
Then you can choose to call on a player to start adding points to.
After looping a certain amount of times and pressing 0, the while loop will cease to run and will skip down to the for loop outputting players name and then points.
Problem: If I input "1" for playerNumber, and I start adding points to index [0][1] and outputs numbers quite different from the original numbers I put in. If there are more than 2 players, 2 of the 3 players have random numbers while one remains an accurate point count.
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
//GLOBAL SCOPE, all loops and other boxes can use these
//Declaration variables w cout & cin.
int playerNumber;
string playerNames;
bool flag = true;
cout << "How many players are there: ";
cin >> playerNumber;
cout << endl;
//Array Declaration.
string playerList[playerNumber][2]; //Dynamic array. changes during program runtime.
int points[playerNumber]; //Dynamic array. Changes during runtime
//GLOBAL SCOPE, all loops and other boxes can use these
//Assigning values to arrays now.
cout << "Enter the players names: " << endl;
//Assigns player name to each row.
for(int i = 0; i < playerNumber; i++){
cin >> playerNames;
playerList[i][0] = playerNames; //Assigns players name to the array
cout << "Player " << i + 1 << ": " << playerList[i][0] << endl;
}
while(flag){
//LOCAL VARIABLES
int choice = 0; //Always reverts back to zero to prevent addition error.
int pointsValue = 0; //Always reverts back to zero to prevent addition error.
//LOCAL VARIALES
cout << "Press 0 to end game, if not, enter player number: " << endl;
cin >> choice;
if(choice == 0){ //Exit out of the while loop
flag = false;
}
else if(cin.fail()){
cout << "Not a number. Try again." << endl;
cin.clear();
cin.ignore(256, '\n');
}
else if(choice < 0 || choice > playerNumber){
cout << "Choice is less than 0 or greater than player count. Try again." << endl;
}
else{
cout << "Enter points: " << endl;
cin >> pointsValue;
cout << endl;
points[choice - 1] += pointsValue; //Assigns points to points array
playerList[choice - 1][1] = (to_string(points[choice - 1])); //Assigns points to playerNumber.
}
}
cout << endl;
cout << "END OF JEOPARDY. HERE ARE THE POINTS!!!" << endl;
cout << endl;
//Current points for each player
//Shows their name and points
for(int i = 0; i < playerNumber; i++){ //Loops so that player name and points are displayed
string playerName = playerList[i][0];
string totalPoints = playerList[i][1];
cout << playerName << " points: " << totalPoints << endl;
}
return 0;
}
Technically, this is illegal:
string playerList[playerNumber][2];
int points[playerNumber];
The size of the array must be known at compile time (not runtime). Though some compilers allow this as an extension to the language, it is not part of the standard language.
Better choice would have been to use std::vector.
Lets assume your compiler allows this:
The next issue is that you don't initialize the values in the array.
int points[playerNumber]; // This is an array of random numbers.
// Sure if you are doing a debug build the
// compiler may be nice and just set all the
// values to zero as speed is not important
// during debugging. But on a release build
// these could be any value.
Also if we want to be technical its actually undefined behavior to read from the array unless you first write a value. Though usally this is not going to cause the program to crash on most architectures and unfortuantely the code just runs like nothing bad is happening.
You can normall initialize the array like this:
int points[10] = {0}; // but your variable size stuff
// will stop working for that.
-------
// so you will have to manually initialize the members
int points[playerNumber];
for(int loop = 0; loop < playerNumber; ++loop) {
points[loop] = 0;
}
Or if you upgrade to vector:
std::vector<int> points(playerNumber,0); // Size and initial value.
// Though you don't need the
// initial value as vector will
// zero init members.
The last issue I will mention is that you are not consistent on checking if the read worked.
cin >> pointsValue;
What do you think happens to pointsValue if the read fails (ie. the user puts in an illegal value). The proper way to check the user input is to put the read inside an if statement.
if ( std::cin >> pointValue) {
// The read worked `pointsValue` has valid user input
}
else {
// The read faild.
// We don't know what the user input should be
}
The other thing to think about is that user input is line based. They add values hit return. So it is a good tactic to exploit that and read user input by the line. Once you have the line parse that and validate input. That way the standard input stream does not go into a bad state.
std::string line;
if (std::get(std::cin, line)) {
// We have a line of user input.
std::stringstream lineStream(std::move(line));
line.clear();
int choice;
if (lineStream >> choice) {
// We have a valid choice from the user.
// or do we. If the user entered `2x` is that valid input?
// because `choice` is 2; but there is still `x` on the
// input stream.
// That's a choice for you as the developer to make.
// if you don't care, then you have valid input. If you do
// care then you need to check there is no bad data on
// the line.
}
else {
// invalid choice
}
}
else {
// The user input stream just ended.
// This could mean the user entered the end-of-stream character
// or if the user had connected some other stream to the
// standard input on the command line and there is no more
// data to read.
}
I would note that this will probably never work for invalid input.
if(choice == 0){ //Exit out of the while loop
flag = false;
}
else if(cin.fail()){
// If you failed to read data from the std::cin
// the the value of `choice` is probably zero
// (if I remember my standard correctly) so the
// first branch of the if tree will be entered
// and you will never enter this branch.
cout << "Not a number. Try again." << endl;
cin.clear();
cin.ignore(256, '\n');
}

How to call the function to pass the value in this code? C++

I am trying to do the homework but I can't figure how to continue from here. The assignment requires to design a calculator for controlling budget. Here are the requirements:
Have you ever been low on cash and couldn’t go beyond a certain dollar limit when shopping? You sort of need a calculator in your head. It would be cool if a device was actually part of the cart and as you add an item into the cart it would increment your total counter. To solve this, we are going to write a program that keeps a tally of the amount that we have spent so far as we visit a store.
What Your Program Should Do:
Allow the shopper (user) to enter in the product name and the cost. This should be echoed and confirmed. Make sure to check for bad data.
The user should be allowed to continue this until they want to check out.
Your program needs to keep a running total.
Upon checkout, the grand total should be displayed.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int item_info(float, char);
int main()
{
//Declare all varibles.
char itemName[100];
float itemPrice;
char option;
float total;
int count;
count = 1;
// Setting decimal point for output.
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(2);
item_info(itemPrice, itemName[100]);
total = total + itemPrice;
//Ask user if they want to continued to add more items.
cout << "Do you want to add more items? (Y/N)";
cin >> option;
if (option == 'Y' || option == 'y')
{
item_info(itemPrice, itemName[100]);
}
else
{
cout << "The total price of all items: $" << total << ".\n";
}
}
int item_info(float itemPrice, char itemName[100])
{
//Ask for input.
cout << "Please enter the item name: ";
cin.get(itemName, '\n');
//Ask for the price of the item.
cout << "Please enter the price of the item: ";
cin >> itemPrice;
//Check if it's a valid data.
while (!cin)
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid input! Please enter the item price:";
cin >> itemPrice;
}
//Only take necessary data.
cin.ignore(100, '\n');
//Confirm the user input.
cout << "Item information:" << itemName <<": " << itemPrice <<"\n";
return itemPrice;
}
Can someone tell me how to fix it ?
You have two obvious problems: First is that the declaration and definition of item_info doesn't match. One takes a single character, the other an array of characters.
The second problem is that you call the function with a single character, but the problem is that you index out of bounds of the itemName array.
My guess is that the function is supposed to take a string (i.e. an array of characters), which means that the declaration and the call are wrong. You should not use an index when calling the function, just pass itemName like any other argument (see e.g. itemPrice).
First of all, your item_info parameters differ in definition and declaration:
int item_info(float, char);//should be char[100]
int item_info(float itemPrice, char itemName[100])
{
<...>
}
Second, here you are passing only the 100th element of the array, not the array itself:
item_info(itemPrice, itemName[100]); //should be item_info(itemPrice, itemName);
Finally, you should really use std::string for that, it will help you avoid such problems.
Your item_info function return an int, and you don't use this return value anywhere.
If you want to use itemPrice and itemName as an in/out parameters, you need to use a reference &.
Also, why not use std::string instead of a char array?
And as the other answers mentions. The declaration and definition of item_info doesn't match.

functions not returning values that a user enters

I AM working on this program for an assignment, so I don't want the answer...just a push in the right direction.
I have written a program in which a user will input a 3-digit ID (required) and an amout of KWh used for the month. After that criteria has been entered, it will print out a short summary + the charges for that month per user. And this is enclosed in a loop to ask if there are any more IDs to be entered.
Below is my opening code and loop structure:
#include <iostream>
#include <string>
#include <iomanip>
#include <windows.h>
using namespace std;
//function prototypes
string get_user_ID();
int get_cust_kwh();
string display_cust_data();
int main()
{
string userID;
int userKWH;
char answer;
while ((answer !='N')&&(answer !='n')){
userID = get_user_ID();
userKWH =get_cust_kwh();
display_cust_data();
cout << "\n\nWould you like to add another utility ID? : (Y or N)";
cin >> answer;
}
}
system("pause")
return 0;
I can get the loop to function correctly, but my functions don't seem to be returning the values that the user enters. As I am new to functions, I am sure it's some silly mistake, but one that has been driving me crazy. Here are the functions:
**********function definitions**********
string get_user_ID(){
string usrID;
cout << "\n\nPlease enter in your 3-digit utility ID: ";
cin >> usrID;
return usrID;
}
int get_cust_kwh(){
int usrKWHs;
cout << "Please enter the total KWH used for the month: ";
cin >> usrKWHs;
return usrKWHs;
}
string display_cust_data(){
string usrID;
int usrKWHs;
double userCharge;
cout << "\n\nUSER ID KWHours Charge($)\n";
cout << fixed << setprecision(2);
cout << usrID << " " << usrKWHs << " " << userCharge << endl;
}
I'm thinking something to do with the way the variables in the functions are used.
Thanks for any pushes you can give!
The problem is display_cust_data() doesn't know about variables in main function scope. What you are printing is just the local variables which has garbage values.
string display_cust_data(){
string usrID; // This is a different variable and is not equivalent to the
// variable in main.
Also why the function's return type is string ?
Look at your display_cust_data. How does it get any information about what to display?
You need to find a way to pass the user input variables to your display function. The variables you have in the display_cust_data() function are newly created there and are not the same as the variables you have in your while loop in your main() function. All of the variables you display in that function are uninitialised and so you have no idea what their values will actually be. Consider adding arguments to the function so that when you call it you can pass the user input variables to it so that you can display the values you want to display.

C++ cin positive integers only

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 accept 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.