Some kind of 'goto' function for C++ [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 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.

Related

reuses "rechnung()" even though it shouldn't

#include <iostream>
#include "funktionen.h"
using namespace std;
int rechnung()
{
cout << "Please choose the operator you want to calculate with" << endl;
int eingabe1;
int eingabe2;
int eingabe;
int dummy;
char zeichen;
char again;
cin >> zeichen;
cout << endl << "1. Eingabe: ";
cin >> eingabe1;
cout << endl << "2. Eingabe: ";
cin >> eingabe2;
switch (zeichen)
{
case '+':
eingabe=eingabe1 + eingabe2;
break;
case '-':
eingabe=eingabe1 - eingabe2;
break;
case '*':
eingabe=eingabe1 * eingabe2;
break;
case '/':
eingabe=eingabe1 / eingabe2;
break;
}
cout << endl << "Das Ergebnis ist | " << eingabe << " | " << endl << endl;
cout << "Wanna calculate again? ";
cin >> again;
while(again=='Y')
{
rechnung();
}
return 0;
}
So this is my code in an implementation file. My problem is, that the main program always loops the whole "rechnung()" function even though I don't type "Y" into the console once it asks for it. In the beginning, when I type something else than "Y", then the console closes (as it shall) but if I do a calculation, type "Y", do another calculation and type "k" for example, it also starts from the beginning of "rechnung()". Why does it do so? I mean I told him that he shall only recall the "rechnung()" if the character input is "Y".
Consider this maybe simpler example:
void foo() {}
void bar() {
char again;
// ... do something
std::cin >> again;
while(again=='Y') {
foo();
}
}
Inside the loop the value of again never changes, so there is an infinite loop. However, your code goes one step further by calling the function recursively. Strongly simplified you have:
void bar() {
// .. do something
while (true) {
bar();
}
}
ie bar is calling itself again and again and never returns. You put the loop at the wrong place. You could write it like this
void bar() {
char again = 'Y';
while (again == 'Y') {
// .. do something
std::cout << "repeat?";
std::cin >> again;
}
}

How to go back to a certain point in the code

I'm new to C++ programming.
I just want to know if there is any way to go back to a certain point in the code without using a while or a do-while loop.
Here is an example:
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {cout << "WRONG! Try again!";}
So, if the player fails, I want to ask the question again, so going back to:
cout << "What's 2+2?";
Is there any way to do it without using a loop?
You want to repeat something until a condition is satisfied. That is the definition of a loop, and there are many ways to write loops in C++. The example you showed is best handled using a do-while loop:
int a;
do
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
while (true);
Though you could use a while or for loop instead:
int a;
while (true)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
int a;
for(;;)
{
cout << "What's 2+2?";
cin >> a;
if (a == 4) {
cout << "Nice!";
break;
}
cout << "WRONG! Try again!";
}
That being said, to answer your actual question, you can use a goto statement without any other looping instructions:
int a;
askTheUser:
cout << "What's 2+2?";
cin >> a;
if (a != 4) {
cout << "WRONG! Try again!";
goto askTheUser;
}
cout << "Nice!";
But, goto is rarely used in modern coding, it is not likely to perform any better than a do-while loop after compiler optimizations are applied, and it has limitations on how it can be used.
The preferred language construct for executing a block of code more than once is a loop, which can be of a for, a do-while, or a while form.
So I'd write the code as follows:
int a;
bool correctGuess = false;
while (!correctGuess) {
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!"; correctGuess = true; }
else { cout << "WRONG! Try again!"; }
}
Another way would be the use of recursion, i.e. a function that calls itself until a particular condition is met. Yet this seems to be a to complicated approach for your scenario.
If - for any reason - you are asked to not use such kind of loops, you could use a goto-statement (though this is clearly not the preferred way to do; goto-statements are very rarely used nowadays):
int a;
loop:
cout << "What's 2+2?";
cin >> a;
if (a==4) {cout << "Nice!";}
else {
cout << "WRONG! Try again!";
goto loop;
}
DontDoThis:
...
goto DontDoThis;
That's it.
DontDoThis: is a "label", and goto DontDoThis jumps execution to the specified label. But, like the label's name says, DONT DO THIS! Using goto is concerned bad practice in modern coding, there are better ways to handle looping.
You should initialize a to 0 and then use a while (a != 4) loop. But that's not your question :)
The other loop statement is for
Another way is to use functions - they can be called repeatedly.
Well, if you don't want to use a while or do-while...
for (;;) //same as while(true)
{
int a;
cout << "What's 2+2?";
cin >> a;
if (a==4)
{
cout << "Nice!";
break;
}
else
{
cout << "WRONG! Try again!";
}
}

How do I loop a variable?

I have made a "program" that just says welcome! Type two numbers you want to be added to each other:
there you type the two numbers and then you get the answer out...
When that is done it says: Press any key to continue . . .
When you press a key the program shuts down, but I want it to restart when you pres any key...
How do I do that? I use Microsoft visual studio express 2013 for windows desktop...
langue is C++
This is my code:
#include <iostream>
#include <limits>
#include <cstdio>
using namespace std;
int Add(int x, int y)
{
cout << "Calculating the sum of " << x << " + " << y << "\n";
return (x + y);
}
int main()
{
cout << " Welcome!\n";
int a, b, c;
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nShutting down....\n\n";
system("pause");
return 0;
}
To loop, you can use while.
For example:
while (false) {
std::cout << "You will never see this output" << std::endl;
}
bool loop = true;
while (loop) {
std::cout << "Type 'quit' to quit this loop." << std::endl;
std::string input;
// This will grab a *single word* from the input. If you want a line, look
// at std::getline
std::cin >> input;
if (input == "quit") {
loop = false;
}
}
while (true) {
std::cout << "This will be repeated forever" << std::endl;
}
There are also two other forms, do while:
std::string input;
do {
std::cout << "Type 'quit' to quit." << std::endl;
std::cin >> input;
} while (input != "quit");
... and for (which is generally used for loop over a defined list of things):
for (size_t i = 0; i < 10; ++i) {
std::cout << i << " out of 10" << std::endl;
}
Technically you can use any of these loop types for any kind of looping, but I suspect the type you want is either one of the two standard infinite loops (whichever one you prefer):
while (true) {
// stuff to repeat forever
}
for (;;) {
// stuff to repeat forever
}
... or a do while loop similar to the do { ... } while (input != "quit"); loop above.
int main()
{
cout << " Welcome!\n";
int a, b, c;
while (true)
{
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress a key to go again....\n\n";
system("pause");
};
return 0;
}
You can do something like this:
int main()
{
cout << " Welcome!\n";
int a, b, c;
while(true) {
cout << "Type two numbers you want to be added to each other: ";
cin >> a;
cin >> b;
c = Add(a, b);
cout << "The answere is: " << c;
cout << "\nPress any key to continue\n";
system("pause");
}
return 0;
}
Use a do while loop mentioning your condition
before exiting the program so that you can determine when to continue and when to exit
I am not sure I understand your question, but I think this is what you are looking for. Have a boolean that determines if the program will loop or not.
int main() {
// stillRun is true while we want to keep looping the program
boolean stillRun = true;
while(stillRun) {
runProgram() ; // this function has all the other code in your old main() function
cin >> stillRun ;
}
}

Reading from/writing to files using functions [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 8 years ago.
Improve this question
Hi I am working on a simple wage application. The following code contains a two option menu using switch statements. The code is also linked to a text file called "shop-account". The file simply contains the value 100.
For option 1 the user is suppose to be able to transfer an amount from the file. The user should be able to make as many transfers as they choose without overdrawing the account. And the code should be able to output the current balance. I believe I am suppose to be using the void function but I have never used it before and am really struggling. I was hoping someone could look at the code and tell me where I am going wrong. Thanks
int read_balance (void);
void write_balance (int balance);
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int selection;
int total;
int balance;
int NewAmount;
do {
cout << "1. Transfer an amount" <<endl;
cout << "2. Quit" << endl;
cout << "Please enter menu number"<<endl;
cin >> selection;
switch(selection)
{
case 1:
cout << "You have choosen to transfer an amount" << endl;
cout << "How much do you wish to transfer from the shop account?"<<endl;
cin >> NewAmount;
balance -= NewAmount;
write_balance (balance);
cout << balance << endl;
break;
case 2:
return 0;
break;
default:
cout << "Ooops, invalid selection!" << endl;
break;
}
}while(selection != 2);
system("pause");
return 0;
}
int read_balance (void)
{
fstream f;
f.open("shop-account.txt");
f >> balance; //error: "balance" is unidentified
f.close();
return balance;
}
void write_balance (int balance)
{
fstream f;
f.open("shop-account.txt");
f << balance;
f.close();
}
Like others mentioned, you didn't declare the int balance in the right scope (function level scope, in this case).
In fact, it looks like you forgot call read_balance alltogether, so your calculations on balance used an indeterminate value, which is Undefined Behaviour.
Next up: declare your variables where they are used, that way you prevent this whole situation when you decide to extract pieces of code into subfunctions, and it gets easier to see where variables are used. Consequently, it gets easier to see whether the code is correct.
Next: Error handling. If you have none, your program is worthless. In fact, even when fixing the above issue,
simply entering invalid input once would run a loop and just keep substracting indeterminate values from the account balance and writing those wrong values to disk. That's probably not what you wanted.
making the shop-account.txt read-only was enough to fool the program into
transfer unlimited amounts without updating the file
having the wrong idea of the balance in the file (since it never checks)
Here is a cleaned-up version that does a minimum amount of checking, and adds an option to just 'check the account balance'. Seemed useful.
See it Live On Coliru
I hope some of this helps. For one thing, I hope your teacher was going to mention most of this :/
int read_balance(void);
void write_balance(int balance);
#include <iostream>
#include <limits>
int main()
{
while(std::cin.good())
{
std::cout << "0. Request balance" << std::endl;
std::cout << "1. Transfer an amount" << std::endl;
std::cout << "2. Quit" << std::endl;
std::cout << "Please enter menu number" << std::endl;
int selection = 2;
if(std::cin >> selection)
{
std::cout << "DEBUG: selection:" << selection << "\n";
switch(selection)
{
case 0:
std::cout << "The current account balance is " << read_balance() << std::endl;
break;
case 1:
{
std::cout << "You have choosen to transfer an amount" << std::endl;
std::cout << "How much do you wish to transfer from the shop account?"<<std::endl;
int amount = 0;
if (std::cin >> amount)
{
std::cout << "DEBUG: amount:" << amount << "\n";
int balance = read_balance();
if(amount<=0)
{
std::cout << "Amount must be positive\n";
}
else if(balance < amount)
{
std::cout << "Insufficient funds\n";
}
else
{
int new_balance = balance - amount;
write_balance(new_balance);
std::cout << "New account balance: " << new_balance << std::endl;
}
} else
{
// bad input cleared outside the switch
}
}
break;
case 2:
return 0;
break;
default:
std::cout << "Ooops, invalid selection!" << std::endl;
break;
}
}
if(std::cin.eof())
{
std::cout << "Bye\n";
return 0;
}
if(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(99999, '\n');
std::cout << "Invalid input\n";
// note eof() can be true here
}
}
}
#include <fstream>
int read_balance(void)
{
std::ifstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop-account.txt");
int balance;
f >> balance;
f.close();
return balance;
}
void write_balance(int balance)
{
std::ofstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop-account.txt");
f << balance;
f.close();
}
your function does not have a balance varible declartion !! you have to add a balance declaration in your function
int read_balance(void)
{
fstream f;
f.open("shop-account.txt");
int balance;
f >> balance; //now it's defined
f.close();
return balance;
}

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