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

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

Related

"Illegal else without matching if" error message c++

I am doing a programming exercise for my beginner class. The exercise is to write a c++ program that mimics a calculator.
This is the beginning of my code (not the entire code, just the beginning):
#include <iostream>
#include <string>
using namespace std;
int num1;
int num2;
double answer;
string op;
int main(void)
{
// Write your main here
cout << "Enter a number" << endl;
cin >> num1;
//Prompt user to enter an operator
cout << "Enter an operator (+, -, *, or /)" << endl;
cin >> op;
//Prompt user to enter another number
cout << "Enter another number" << endl;
cin >> num2;
//Determine whether or not addition was selected
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
Regardless of what statements I put after that "else" statement, I am getting an error message that reads "Illegal else without matching if."
BUT, if I remove the preceding "cout << answer;" line, then the program compiles and runs fine.
What am I doing wrong?
Always use scope { ... } with if statements and for/while loops.
The problem is, if you don't use scope, then your if only encompasses the next statement underneath it (answer = (...). Because of this, the cout statement will happen ALL THE TIME, and the else isn't associated with the if statement. If you always use scope, you never have to worry about this.
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
You need to use {} braces on your if statement in order to execute multiple statements:
//Determine whether or not addition was selected
if (op == "+")
{
answer = (num1 + num2);
cout << answer;
}
else
...
You need to add the {} brackets between if and else because you have more than one statement.
This is what the compiler understands from your code:
if (op == "+")
answer = (num1 + num2);
cout << answer;
else
What you should do:
if (op == "+") {
answer = (num1 + num2);
cout << answer;
}
else

Stuck on infinite loop

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

How do I keep asking the user a question over and over again until they enter the correct field of value?

I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}

Some kind of 'goto' function for C++ [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 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
switch(operation)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
here
}
else if(response=='N')
{
cout << "The program will now close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
Where the word 'here' is written, I want to insert a code that gets you to the beggining of the code.
You can use the loop do... while(condition)
Like :
do{
cin >> a >> operation >> b;
switch(operation)
{
...
}
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
}while(response=='Y');
If the response isn't 'Y' the loop ends, if it is the loop begin again
All though goto is highly frowned upon in C++, it does exist.
Much like assembly, your put a label in your code and then tell it to 'jump' there using goto. However, the same way jump works in assembly, this may break you out of all loops to the point that you jump to.
#include <iostream>
using namespace std;
int main()
{
label:
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
cin >> response;
if(response=='Y')
{
goto label;
}
else if(response=='N')
{
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
}
return 0;
}
What most people would do is use a do{}while(condition==true) loop or just an infinite loop while(true).
For this 'neater' code, what you would do is
#include <iostream>
using namespace std;
int main()
{
do{
float a, b, result;
char operation, response;
cin >> a >> operation >> b;
//condensed for neatness
// Output result
cout << "The result is " << result << endl;
system("sleep 200");
cout << "Do you want to make another opertaion? (Y/N)" << endl;
}while(cin.get() == 'Y');
cout << "The program will no`enter code here`w close" << endl;
system("sleep 500");
return -1;
return 0;
}
If this is being called from another location, I would highly recommend using do while rather than goto, as it can cause issues.
The only real problem with goto is that it's not elegant and makes code confusing to read. You should use loops and returns where possible, and only use goto if you see no other way to make this work optimally.

How to loop after a loop statement is completed?

int guess_number = (gen() % 1000);
cout << guess_number;
int number = 0;
cout << "Number:";
cin >> number;
do
{
if (number>guess_number)
{
cout << "Too High"<<"\n";
cin >> number;
}
else if (number<guess_number)
{
cout << "Too Low"<< "\n";
cin >> number;
}
} while (number != guess_number);
int again=0;
cout << "Wanna Play Again!";
cin >> again;
I'm making a guessing game, but must loop the game if the player answers 1 after "Wanna Play Again!" I'am working with if,for,do, switch, and while statements. Its an assignment I was given and I just can't seem to figure out exactly how to loop the entier statement. I have made several attempts, but it either exits the program or continually prints "Wanna Play Again!".
How about wrapping the existing do/while with a another for the play again condition ?
int again =0;
do{
do{
//existing code
} //end inner while
cout << "Wanna Play Again?";
cin >> again;
} while(again != 0); //or whatever makes sense for the condition