switch between if/else blocks on error - c++

I'm looking for a way to switch between an if and an else block when an error occurs. For example:
cout << "Enter 1 or 2 as your choice...";
cin >> choice;
if(choice==1) {
//do something here
//if error occurs....
} else if(choice==2) {
//switch to this else block
}
I've played around with try/throw/catch but it appears that the catch has to follow the try statement. Any ideas/suggestions would be appreciated!

When I come across this situation, I create a separate function with the code wanted in the else block. Then I call the function whenever needed (if an error occurs, and in the else block).

Looks like you could just not have an "else":
int error = 0;
if( choice==1 ) {
// Something happens
error = 1;
}
if( error == 1 || choice == 2 ) {
// Do things
}

You really want to split that in to two different conditional blocks. After all, you don't really mean "else".
if(choice==1)
{
//if error occurs....
}
if(choice==2 || error)
{
//switch to this block
}

Related

Else for multiple if's

Is it possible to make multiple if's and one else for all of them without using the bool variable? I'm talking about something that works like this:
bool triggered = 0;
if (condition)
{
//code
triggered = 1;
}
if (condion2)
{
//code
triggered = 1;
}
if (!triggered)
{
//code
}
So if none of these if's happened - something happens. In pseudo-code I would write it like this:
{
if()
{
}
if()
{
}
}
else
{
}
Is there a possibility to make something similar?
No, you can't do it like that. You can do:
if (condition1 || condition2) {
if (condition1) {
//code
}
if (condition2) {
//code
}
} else {
// code
}
But this means you have to test condition1 and condition2 twice. And if there are lots of conditions, the first if will be very long.
I find your code with the triggered variable preferable. Often, there's already a variable that serves the purpose. For instance, form validation code often looks something like this:
std::string errors;
if (field1 is invalid) {
errors += "Field1 is invalid\n";
}
if (field2 is invalid) {
errors += "Field 2 is invalid\n";
}
if (errors == "") {
// process the form
} else {
// display error message
}

How to make a try catch recursion in a switch statement iterative?

I am trying to make a function that looks like below. I want to make it iterative, but I am not sure since I need to keep all paths open.
someFunction( parameters)
{
//do stuff
switch( thing )
case: one
if (something true)
{
try { someFunction( different parameters ) } catch(...) { throw }
case: two
//if else with the else being a throw exception.
case: three
// same
case: four
...
default
return some value
I didnt understand very well ur question, but i will try to help!
How to use EXCEPTIONS:
...
try
{
if(b == 0)
throw("A number cannot be devided by zero!\n");
c = a/b
}
catch(string error)
{
cout << "ERROR: "<< error << endl;
}
return c
...
You could use it in a switch statement, after the catch i will return to the case.
switch(c)
{
case 0:
...
try { ... throw();}
catch() { ... error treatment}
...
break;
case 1:
...
}

understanding break statement and handling it for existing code

In the below example, i have problem in handling the break statement. For country = US, somearray will be of length one only. but in case of "DE", length is more than one. but given program, since break statement is used to get out after processing 1st row, it will not suite for DE country since DE country has more than one rows Since re-
using is a better way, checking if there is someway i can re use the same logic for country =DE as well
if(country == "US" || country == "DE")
{
for(int i = 0; i < somearray.length(); i++)
{
if( (payment == "USD") )
{
if(amount > 0)
{
//do something
}
if( balance.is_positive())
{
// do something
}
break;
}
}
}
Note : this is not actual code.. just wrote like an example to understand..
if(country = "US" || country = "DE")
{
for(int i = 0; i < somearray.length(); i++)
{
if( (payment == "USD") )
{
if(amount > 0)
{
//do something
}
if( balance.is_positive())
{
// do something
}
if(somearray.length()==1) // as per Your requirement country **us** has **length 1** ,in this can break the loop
{break;}
}
}
}
From what I have understood, You want to process each element in somearray, Therefore removing break statement will suffice. if (payment = "USD") is useless here, a simple statement payment="USD" would suffice. Moreover since that is an assignment which is same for all the loop iterations, pull it outside and assign before the loop.

i keep get this "error C2059" C++

I am getting this error
error C2059: syntax error : 'if'
This is my code
// N.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
int main ()
{
int x,y,n,i,m;
std::cout<<"please enter a number";
i=0;
std::cin>>n;
for (x=1;x=n;x++)
for (y=1;y=n;y++)
if (x=y) m=x;
else;
while (x!=y) ;
do
{
if (x>y) x=x-y;
else y=y-x;
m=x;
}
if (m=1) i=i+1;
std::cout<<i;
return 0;
}
what is the problem ?
I am using microsoft visual studio 2008
The problem is that after the do { ... } the compiler is expecting a condition:
do
{
if (x>y) x=x-y;
else y=y-x;
m=x;
} while (condition);
In addition, your code seems to be not correct at all. For instance, your if (x=y) condition may be like this: if (x==y), and other...
You have errors in your for statements.
Use == for comparison, not = which is assignment.
Also, use < or <= as comparison. The == condition may be skipped over in loops.
A suggestion to help prevent these issues in the future: Use '{' and '}' with for, if, else and while.
For example:
for (x=1;x=n;x++)
{ // Insert this line.
for (y=1;y=n;y++)
{ // Insert this line.
if (x=y)
{
m=x;
}
else
{
;
}
} // End of for y
} // End of for x
The braces and indentation help spot errors during code reviews. Most coding styles demand the braces, even for single statements.
Also, use spaces to make code more readable. They don't impact the build time or code generation, but really help when reading the code:
for (x = 1; x <= n; x++)

Changing while loop to accommodate two situations

Suppose I have a while loop that depends on two separate inputs. In situation one, the while loop will take the value 1, and in situation two, it should take !cin.eof(). Is there a way I can do this efficiently? To be more concise:
string hello;
cin >> hello;
if(hello == "one")
{
//make the while loop depend on value 1
}
else if(hello == "two")
{
//make the while loop depend on value !cin.eof()
}
while(/*depends on above conditional*/)
{}
I don't want to do something like:
if(hello == "one)
{
while(1){}
}
else if(hello == "two")
{
while(!cin.eof){}
}
because the while loop essentially does the same thing in each situation.
For readability and in the interest of cohesion, I think you should move the contents of your loop into a separate function:
void DoSomething() { /* ... */ }
// ...
if(hello == "one)
{
while(1){ DoSomething(); }
}
else if(hello == "two")
{
while(!cin.eof){ DoSomething(); }
}
It's easier to see that the different while loops are doing the same thing but their conditions are different.
I believe you're looking for something like this:
while((hello == "one") || (hello == "two" && !cin.eof)) {
}
This code will do what you want, because it checks 'is the variable "one"? If so, keep executing. If it's not, it'll check: Is the variable "two"? If so, it'll check for cin.eof.
If it's neither, the loop won't execute. (the && 1 in the first condition was omitted, because it's always 'true', equalling and infinite loop)
Edit:
To simplify things, you may want to consider this code (as suggested in the comments):
bool HelloIsOne = (strcmp(hello, "one") == 0);
bool HelloIsTwo = (strcmp(hello, "two") == 0);
while(HelloIsOne || HelloIsTwo && !cin.eof) {
}
The brackets, which I placed in the previous example are actually unnecessary, because && binds stronger than ||, but they help the general clarity of the code.
Simply use or (||) as a condition in the while loop. Set the first condition if(hello == "one"). Now you have a while loop that will loop if one of the conditions is true.
bool value = hello == "one";
while (value || !cin.eof) {}
If you're using C++11:
#include <functional>
auto check = (hello == "one") ? []() bool -> { return 1; } :
[]() bool -> { return !cin.eof(); };
while(check) {
};
How about this:
switch(hello)
{
case 'one':
{
for(; 1; );
{
// your loop here
}
break;
}
case 'two':
{
for(;!cin.eof; )
{
// your other loop here
}
break;
}
default:
{
cout << " shouldnt get here unless bad user input" << endl;
break;
}
}
You can do something like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string hello;
cin >> hello;
while(hello=="one"?1:(!cin.eof()))
{
//do stuff
}
return 0;
}
It checks if the string hello is "one" and if it's true, the condition of the while is 1, else it is !cin.eof() as you wanted.