Stuck on infinite loop - c++

noob programmer here. Taking my first CS class in college and making first post on here so excuse me if the info i provide is not sufficient in advanced.
Still trying to figure out loops. Seem to get it but once there is loops within loops or if statements inside loops, I get thrown off and have no idea on how to proceed. For my assignment, I need the following to occur.
Would you like to process all the records in the file? (y/n) W
Please enter either y or n.
Would you like to process all the records in the file? (y/n) n
Enter number of records to process: two
XXXXXXXXXX Error-non numeric or negative value, try again
Enter number of records to process: 10
Here is my code:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
do{
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
}
else{
notDone = false;
}
}
}else if(a != 'y' or a != 'n');
cout <<"Please enter either y or n." << endl;
}while( a != 'y');

Most problems are explained in comments, here is how I would fix it:
char a = 0; //User chooses Y or N
int ProcessAmount = 0; //Amount of times to process if not all
cout << "Would you like to process all the records in the file? (y/n) ";
cin >> a;
while (a != 'y') {
bool notDone = true;
if(a == 'n'){
while(notDone){
cout << "Enter records to process: ";
cin >> ProcessAmount;
if (cin.fail()){
cin.clear();
cin.ignore(40,'\n');
cout << "" << endl;
} else {
notDone = false;
}
}
} else if(a != 'y' or a != 'n') {
cout <<"Please enter either y or n." << endl;
cin >> a; // Need to get new input because old one is invalid.
}
};
Also I don't see how notDone is used. Also I would strongly advise of using proper indentation, spaces around keywords as while, for, if, else as it is good style.

You just put the y/n solicitation out of your loop then 'a' won't never change its value. Take a look of the change you may want:
do {
cout << "Would you like to process all the records in the file? (y/n/f) "; //f to break the loop
cin >> a;
bool notDone = true;
if (a == 'n') {
//. . .
} else if (a == 'y') {
//You may want to do something when yes
} else if (a != 'f')
cout <<"Please enter either y/n or f." << endl;
} while( a != 'f')

Related

How can I stop input repeating for each char inputted?

I'm trying to write a prompt where it asks the user to confirm an operation, with Y/N as the only two options.
If the user inputs Y, it does something, if the user inputs N it does something else. However if the user inputs anything other than Y or N, it simply repeats the question until either Y or N is pressed.
This is what i've got so far:
char result = '\0';
while (result != 'y' || result != 'n')
{
char key = '\0';
cout << "Do you wish to continue & overwrite the file? Y/N: ";
cin >> key;
result = tolower(key);
}
if (result == 'y')
{
cout << "YES!" << endl;
}
else if (result == 'n')
{
cout << "NO!" << endl;
}
And my problem is that if I enter multiple invalid characters, it displays the prompt again for each invalid character, like so:
Do you wish to continue & overwrite the file? Y/N: abc
a
Do you wish to continue & overwrite the file? Y/N: b
Do you wish to continue & overwrite the file? Y/N: c
Do you wish to continue & overwrite the file? Y/N:
What am I doing wrong?
So if my input was stored as a string (rather than a char), I wouldn't get the repetition for each char inputted. Also, my while loop condition should have been AND instead of OR:
string result = "";
while (result != "y" && result != "n")
{
cout << "Do you wish to continue & overwrite the file? Y/N: ";
cin >> result;
transform(result.begin(), result.end(), result.begin(), ::tolower);
}
if (result == "y")
{
cout << "YES!" << endl;
}
else if (result == "n")
{
cout << "NO!" << endl;
}

Trouble with guessing game

I need to do a Guessing game where the program generates a random number and the user has to guess the number. If the user guesses the number in less than 10 guesses the program congratulates them and lets them know they were under 10 guesses. If they were above 10 guesses then it lets them know it was above 10, etc.
The problem I'm facing is if, for example, the user guesses the number in 3 tries and then decides to play again with a whole new other number, and this time guesses it in 8 tries, instead of still congratulating them because it was under 10 tries, it counts the 3 tries from the previous game. This then leads the program to tell them they were over 10 tries, even though they were not. I don't know how to fix this. The code I've done so far is as follows:
int main()
{
srand(time(0));
int guess;
int number;
char selection = 'y';
int numberOfGuesses=0;
while(selection == 'y' || selection == 'Y')
{
number = rand() % 1000 + 1;
cout << "I have a number between 1 and 1000.\nCan you guess my number?\nPlease type your first guess: ";
cin >>guess;
do
{
if(number > guess)
{
cout << "Too low. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
if (number < guess)
{
cout << "Too high. Try again: " << endl;
cin >> guess;
numberOfGuesses++;
}
}
while(number != guess);
if(numberOfGuesses < 9)
{
cout << "You guessed the number in less than 10 guesses!\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses > 9)
{
cout << "You guessed the number\n Would you like to play again (y or n)?";
cin >> selection;
}
else if(numberOfGuesses == 9)
{
cout << "You guessed the number.\n Would you like to play again (y or n)?";
cin >> selection;
}
}
return 0;
}
The problem is that you are not resetting the counter.
Just put int numberOfGuesses=0; within the while loop:
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses=0;
....
}
You need to set numberOfGuesses to 0 before every game. Your program only sets it once when the program first launched.
You are not resetting numberOfGuesses to zero after each round. You can solve the problem using one of couple of methods.
Reset the value of numberOfGuesses to zero at the end of the first while loop.
while(selection == 'y' || selection == 'Y')
{
...
numberOfGuesses = 0;
}
Don't define the variable until the start of that while loop. Define it as the first statement and initialize it zero.
while(selection == 'y' || selection == 'Y')
{
int numberOfGuesses = 0;
...
}

C++: Asking the user to enter a new number if the number they entered is wrong

I'm trying to get the program to loop again, up to three times, if the user entered a number that does not follow the function defined in the if statement. The code as is, only loops once and then exits. Did I type the for loop incorrectly or is it the if...else statement that is wrong?
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
for (int a = 0; a < 3; ++a);
cin >> num;
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
}
else cout << "That is incorrect, try again!" << endl;
}
}
Did I type the for loop incorrectly or is it the if...else statement that is wrong?
Both. You should (1) remove the semicolon following the for statment; (2) move cin >> num into the for loop body; (3) add break; inside the if.
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
BTW1: Try to use the debugger, then you'll find out what happened in fact.
BTW2: The code will fail when cin >> num fails (e.g. user entered an invalid value), you might need to check the result of cin >> num, to process the case. Such as:
for (int a = 0; a < 3; ++a)
{
if (cin >> num)
{
if (num < 40 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl;
break;
}
else cout << "That is incorrect, try again!" << endl;
}
else
{
cin.clear(); // unset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
cout << "Wrong input, try again!" << endl;
}
}
bool isValid = false;
int num;
while(!isValid)
{
cout << "enter a positive odd integer " << endl;
cin >> num;
if(num < 40 && num > 0 && num % 2 == 1 )
{
cout << "thank you"<<endl;
isValid = true;
}
else
isValid = false;
}
Why not use some thing like this, it will loop until isValid = true which will only happen when your conditions are met?
I understand I guess, if you're doing a school project or some thing and you're forced to do it with a for loop but in general this would be a much better solution for some thing like this than a for loop!

C++ - Loop function or program forever? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here

track how many times an if statement was used true

I think the question speaks for itself, I'm writing a program in c++ and there is a part where the console asks the user which type of input they want to use
while (loop == 5) {
cout << "\nWould you like to enter a depoist or a check? "; //asks for a choice
cin >> choice;
//determines whether or not to close the program
if(choice == 0 || depo == 0 || check == 0) {
return 0;
}//end close if
//choses which type of input to make
if( choice == 1) {
cout << "\nPlease enter check amount: ";
cin >> check;
check += check;
} else if(choice == 2) {
cout << "\nPlease enter deposit amount: ";
cin >> depo;
depo += depo;
}//end if
}
but how do i keep track of how many times the if statement was true?
You can add a counter and increment it every time you enter the if-statement's true block.
int true_counts = 0;
while (loop == 5){
...
if( choice == 1){
true_counts++;
...