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
Related
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;.
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.";
} } }
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)
{
...
}
This question already has an answer here:
How to reset std::cin when using it?
(1 answer)
Closed 5 years ago.
int departmentNo;
bool depNumIncorrect = false;
do
{
depNumIncorrect = false;
cout << "Please enter your department number... ( 1 / 2 / 3 )" << endl;
cin >> departmentNo;
if (departmentNo < 1 || departmentNo > 3)
{
cout << "Invalid Entry." << endl;
depNumIncorrect = true;
}
} while (depNumIncorrect == true);
Whenever I input a correct input (1/2/3), the code works fine and continues without looping. Whenever I input an incorrect integer, the code loops as it is supposed to. But when I input a character or a string, it puts the code into an infinite loop. The "Please enter your department number... ( 1 / 2 / 3 )" is repeatedly output to the console.
How could I go about changing this so that it doesn't start an infinite loop when a character or string is input, but rather loops as it is supposed to and allows me to input again?
deparmentNo is (I assume) an Int and you have a problem of conversion. As mentioned by others you should clear error flag of std::cin. Moreover you probably should not cin directly into an int but rather to a string , and then attempting conversion to int. The result of conversion attempt (successful or not) would be an additional criteria to check for valid entry
i am not very sure the while(choice == 1 || choice ==2);
can anyone explain. i understand this
if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);
i just don't understand the code after this. can anyone explain to me please.
int main()
{
//declare variable and array
int choice = 0;
double rainfall[12] = {0.0};
//get rainfall amounts
for(int x =0;x<12;x++)
{
cout << "Enter rainfall for month "<< x+1<< ": ";
cin >> rainfall[x];
}
do
{
//display menu and get menu choice
cout <<endl;
cout << "1 Display monthly amounts" << endl;
cout << "2 Display total amount" << endl;
cout << "3 End program" << endl;
cout << "Enter your choice : ";
cin >> choice;
//call appropriate function or end program
if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);
}while (choice == 1 || choice ==2);
return 0;
}
It's telling you to keep looping as long as the choice is 1 or 2, but it's entirely separate from the if statement.
Could also be coded as
while(true) {
cout stuff...
if(choice==1)
...
else if(choice==2)
...
else
break;
}
Which may be a little more readable but some old schoolers will freak right out if they see while(true)--that used to be drummed into people as a big red flag indicating a potential bug (Apparently by anyone completely unable to analyze code since the functionality is no different).
This is a do ... while loop. The idea is that the code within the block will continue executing as long as the condition (choice == 1 || choice ==2) is true.
Here is more information from a cplusplus.com article on Control Structures:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.
The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.
You can also think of is this way. You might use a do-while structure if you always want the code within the block to be executed at least once. This is exactly the case in your program since you always want to display the prompt, and can only decide whether the loop will continue after you receive and process the user's input.
In this app, if the user hits 1 or 2, it means that they wanted to see either monthly or total rainfall. What this implies is that they haven't requested to 'End program'. The code assumes that if the user has chosen 1 or 2 that they should continue using the application. If they have chosen ANYTHING else, (eg. 3, just like the menu says) then the condition choice == 1 || choice == 2 will evaluate to false and the loop with terminate, resulting in the application closing.
Basically what the do ... while loop here does is keeps repeating its self as long as the choice is 1 or 2.
After the 'do', the user is prompted to enter their choice, 1 2 or 3. If they choose 1 or 2, their respective function is called. Then the loop repeats. If they choose 3, the loop does not repeat so the program ends.
Hope this helped!