So, I'm trying to create a program that has a never ending while loop unless the user pressing a certain key to exit. Now I'm pretty sure that I need to use a while loop but I'm not 100% sure how it works. I've been trying to add error messages to. The user is suppose to enter a numbered grade and it calculates the gpa but I need to validate the user input to make sure it is numeric and between 0 and 100 but after I put the error message in the loop it just is never ending (literally it shows the message down the page over and over without me touching anything)
could someone explain?
int main()
{
int grade; // input
char y; //determines what letter to press to exit
bool validGrade = true; //determines if grade is valid
cout << "Enter percentage grades to convert to grade points. Press [y] to exit.";
cin >> y;
while(validGrade)
{
cout << "Percentage Grade: ";
cin >> grade;
if (!validGrade)
{
cout << "* Invalid input. Please try again and enter a numeric value.";
}
}
}
this is my code^
A C++ while loop,
while (condition) statement
Will repeatedly evaluate statement while condition evaluates to true.
A common issue that results in infinite loops is creating a program that never modifies condition such that it becomes false. For example, in your program, the condition is validGrade, which you've initialized to true. Do you ever modify validGrade? If not, the condition will remain true forever, and thus loop forever.
You mentioned performing checks on grade, but it seems like you haven't implemented them yet. Think about how you could modify the condition variable to ensure that the loop terminates eventually.
I'd also encourage you to read some tutorials to gain a better understanding of while loops. Here's one to start you off.
Your while loop condition has been initialized to true. So it is supposed to run indefinitely. Based on your question, I think what you're trying to do is to check input stream:
int main() {
int grade; // input
char y; //determines what letter to press to exit
bool validGrade = true; //determines if grade is valid
cout << "Enter percentage grades to convert to grade points. Press [y] to exit.";
cin >> y;
while(cin >> grade) {
cout << "Percentage Grade: ";
if (!validGrade) {
cout << "* Invalid input. Please try again and enter a numeric value.";
} } }
Related
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.
In my c++ code, I would like to validate my user input to be an int between 1,10 using a do while loop. I am able to validated for integers outside of the range. However if user inputs a float or a letter, it becomes an infinite loop. My idea is to add a condition in my while loop for if the input is not an integer to keep asking for input.
the CAPITAL letters is where I am having trouble.
#include <iostream>
using namespace std;
int main(){
cout << "Welcome, ";
int steps;
int count=0;
do{
cout << "How many? \n";
cin >> steps;
IF (STEPS IS NOT INTEGER==TRUE){
COUNT=1;
}
if (steps <1)
{
cout << "not enough...\n";
}
if (steps > 10){
cout << "too many steps.\n Please pick a lower number of steps.\n\n";
}
} while (steps < 1|| steps >10 || COUNT==1);
//doing stuff with valid input
return 0;
}
Essentially I am trying to add another condition that just returns a boolean. and if the boolean implies that the input is not valid, then it reassigns count to make sure the do while loops continues until the input is valid.
The problem i am working on asks for a max and min steps, since all of them were having a similar problem i tried to simplify it and forgot some of the edits.
You can check whether the input failed, i.e. the user entered something that could not be read as an int like this:
if (cin.fail()) { // in place of IF (STEPS IS NOT INTEGER==TRUE)
cin.clear();
cin.ignore();
cout << "not an integer, try again\n";
continue;
}
This avoids the need for the COUNT variable.
Also, your while condition doesn't appear to match the checks inside the loop. What happens when step is either 9 or 10? You should be consistent with the checks inside the loop.
You could use the ! operator.
For example:
if ( !(std::cin >> steps) )
{
std::cin.clear();
std::cin.ignore();
std::cout << "Incorrect entry. Try again: ";
}
Also consider not using using namespace std;.
I just completed a program that has to quit when a negative value is entered as input. Everything is working good except for only one issue, it quits the program after the second time a negative value is entered. After some research I noticed the use of break, however the samples I have to guide the assignment use only if and else statement.
#include <iostream>
using namespace std;
int main()
// insert code here...
// create a variable named "pounds" that can be used to store an integer.
// wait for the user to type in a value and put that value into the variable ounces
{
int poundsTotal;
int ouncesTotal;
while (poundsTotal >= 0)
{
cout << "Enter pounds or a negative number to quit: ";
cin >> poundsTotal;
ouncesTotal = poundsTotal * 16;
cout << poundsTotal << " pouds is " << ouncesTotal << " ounces." <<endl;
cout << " Enter pounds or a negative number to quit ";
cin >> poundsTotal;
poundsTotal++;
}
if (poundsTotal == 0){
cout <<"you enter a zero value" <<"Try onemore time";
}
else {
cout << "you chose to quit the program" <<poundsTotal;
}
}
The condition of a while loop is evaluated after the body has been executed. Then it is determined whether the body will be run again. Change your code and add an if statement inside the loop.
if(poundsTotal < 0) break;
And yes, a break statement is useful in a loop. Otherwise you can't stop the loop before your test condition is evaluated to false.
In your case, I find using a break would be a simple option.
When the program first reaches while (poundsTotal >= 0), poundsTotal has no defined value. This puts you at the mercy of the gods as to whether the program will work as expected or not, and Gods are notoriously unreliable. For more information, look up the term Undefined Behaviour.
The solution to this is ask the user for poundsTotal before the loop and once more at the end of the loop.
If you want to get really posh and do this without repeating code (and stay DRY) , make a function that gets poundsTotal from the user and call this function in the while loop's condition. For example,
while ((poundsTotal = getPoundsTotal()) >= 0)
{
...
}
My problem here is when the loop is broken after the user indicates they're done, the program then begins to print the last input infinitely. What's going on here? I've tried using break, return 0, setting loop = a, all results in the same thing. On a program earlier I used a for loop (used break) and it terminated just fine.
Note: This post is NOT up for syntax corrections, this is just a fragment, and the code runs fine until I terminate the loop. I'm wanting to know what's causing this to happen with a while-loop specifically.
Edit: Nevermind, figured out what was going on. When attempting to end the loop there was a datatype error (as you can see, we only receive input for two variables, both of which are ints), which caused the loop to the start repeating the last valid datatype entered. So my question is why does this happen with a data type error?
`
while (loop != "a")
{
cout << "Enter the first number: ";
cin >> input1;
cout << "\nEnter the second number: ";
cin >> input2;
cout << input1 << '\t' << input2 << '\n';
if (loop == "|")
{
break;
}
}`
Change the value of loop with in the block of while loop according to your condition if loop=="a" or loop =="|" then while loop will be terminated.
In the given code of you the value of loop is not changing therefore while loop will run infinite.
I hope you can understand.
It might be because you entered a wrong data type into 'cin'. This makes cin fail and it repeats the last acceptable value in the command prompt. Nothing to do with the loop. If you try it outside of the loop you'll see the same thing happen.
It's good practice to do the following:
while (!(cin >> input))
{
cin.clear();
cin.ignore(256, '\n');
cout << "Bad input. Try again: ";
}
so if cin fails - it will clear the fail status, ignore the last input and ask the user to enter his input again.
Hope this helps
I had a question in regards to a beginner assignment I was working on. The initial assignment requires me to make a program that asks the user to enter any number other than 5 until the user enters 5. If they enter 5 the program will alert them saying they input 5.
The next part of the assignment requires me to make a condition where after 10 iterations or 10 inputs of a non 5 value, the program messages the user and exits the program.
I finished the first part but had trouble with the second part. I searched stackoverflow and found something about the "get" function, but I'm not sure how to implement it correctly. How would I track the number of inputs or iterations and make a condition to where after n number of successful iterations the program exits?
Also , how would I make a condition to where if the user inputs a character instead of an integer the program warns the user and exits?
Thanks for the help. Here is the code I have written so far.
// This program works, however, if user inputs a character or a very large number
//then the program malfunctions.
// Learn more about the get function.
#include <iostream>
using namespace std;
int main()
{
int inpt;
cout << "Please input any number other than 5.\n";
cin >> inpt;
while (inpt != 5)
{
cout << "Please input another number other than 5.\n";
cin >> inpt;
}
if (inpt = 5)
{
cout << "Hey! You weren't supposed to enter 5!";
}
return 0;
}
you need to add a counter
int count = 0;
increment it each time round the loop
cout << "Please input another number other than 5.\n";
cin >> inpt;
count++;
and stop if the count gets too big
if(count>10) break;
you could also change your while condition
Note
if(inpt = 5) doesnt do what you think, you mean inpt == 5