Self-imposed try/catch for unwanted integers - c++

Try and catch statements are easy for actual exceptions, but how might I write a try/catch for a self-imposed restriction?
For example, if I am getting an integer from cin that I want to be either 2,4, or 7, and anything else to print "That number is not valid" and try again, how would this get written in c++?

#Adam Rosenfield is right: exceptions should be reserved for exceptional situations -- i.e., things you don't expect to happen (or at least not very often). A user entering bad data is expected to happen -- frequently.
Since you always want to read the input at least once, this is a situation where a do/while loop makes sense:
do {
std::cin >> number;
} while (number != 2 && number != 4 && number != 7);

You could probably do this using a simple while loop:
while (true) {
int value = /* ... read a number ... */
if (value == 2 || value == 4 || value == 7) break;
/* ... report an error ... */
}
You are correct that you shouldn't be using try/catch here. Those are heavyweight primitives for dealing with truly unrecoverable errors. In this case, this simple lightweight loop should work just fine.

Related

While function doesn't work like I want it to

Had a new problem with the while function. As easy as it sounds, I still can't wrap my head around it.
Like my last program, this one closes unexpectedly after the correct and wrong messages.
I want this to loop after entering a number, so that the program won't stop.
Thanks for the help, if any.
#include <iostream>
using namespace std;
int main()
{
int X = 0; //setting the first variable
int num; //setting the second
while (X == 0) //this should happen whenever X is equal to 0
{
cout << "Type a number bigger than 3. "; //output
X++; //This should increase X, so that the next while function can happen
}
while (X == 1) //again, since I increased x by one, (0+1=1 obviously) this should happen
{
cin >> num; //standard input
if (num > 3) //if function: if num is bigger than three, then this should happen
{
cout << "Correct! Try again!" <<endl; //output
X--; //Here I'm decreasing x by one, since it was 1 before, now it becomes 0. This should make the "while (X == 0)" part happen again, so that another number bigger than three can be entered
}
if (num <= 3) //if function: if num is lesser than or equal to 3, this should happen
{
cout << "Wrong! Try again!" <<endl; //output
X--; //This is supposed to work like the "X--;" before, repeating the code from "while (X==0)"
}
}
}
now it becomes 0. This should make the "while (X == 0)" part happen again
Nope. While loops don't magically take effect at any point during execution of the program. You only enter a while loop when you've reached it from code above. Programs are executed top-to-bottom, generally.
You would need a loop around the entire program if you want to keep going round and round. Those whiles you have now should probably be ifs.
Merge the two while loops into one, while(true).
Put each previous while body into an if state with the clause from the old while in it.
while(true) {
if (X==0) {
// the X==0- case
} else if (X==1) {
// the X==1 case
}
}
in order to end your loop, do a break;.
You have to think of C++ programs as a sequence of instructions, like a recipe. while just means a loop: you check the condition. If true, you run the body. After running the body, you check only that condition again, and run the body if true. Whenever the condition is false at the start or end of the body of the while (the {} enclosed code after it), you end the loop and proceed to the next one.
The first loop runs, finishes, then the second loop runs in your code. Once the first loop exits, you do not go back into it just because the condition becomes true.
Understanding flow control is one of the "hard" steps of learning to program, so it is ok if you find this tricky.
There are many improvements you can do your code beyond getting it working -- there is, actually, little need for X at all. But baby steps! Once you get it working, you can ponder "how could I remove the variable X?".
Before making such fundamental changes to your program, you should get it working, and save a copy of it so you can "go back" to the last working version.
You want to wrap all that code in it's own while loop:
while (true /* or something */)
{
while (X == 0) //this should happen whenever X is equal to 0
{
// ...
}
At least put your second while loop inside the first one to get it working as intended. Otherwise your program has no reason to go back again.
Nevertheless it's not a good design.

C++ simple If statement making the rest of the program not execute

I have an assignment where I must read from a file and perform various calculations on it and write the answer to an output file. Everything was going great until I came to this step:
"Reread the file and compute the sum of the integers in the file as long as the sum does not exceed 1000. Use a flag controlled loop structure."
My code snippet is as follows:
dataFile2.close();
dataFile2.clear();
dataFile2.open("J:\\datafile2.txt");
sum = 0;
while(sum < 1000)
{
dataFile2 >> num;
sum = sum + num;
if(sum > 1000)
sum = sum - num;
}
answers << "The sum of the integers not exceeding 1000 is " << sum << endl;
cout << "The sum of the integers not exceeding 1000 is " << sum << endl;
return 0;
My variables have already been declared. when I take out the if statement the sum adds the last number and the sum then exceeds 1000. When the If statement is left in, the answers and cout statements are not executed and there are no compiler warnings or errors.
Any help on this would be greatly appreciated.
-ThePoloHobo
Since no one seems to want to give you a correct answer... (and
to be fair, it's hard to give a correct answer without actually
doing your work for you).
There are two issues in you code. The first is the requirement
that you use a flag. As I said in my comment, the idiomatic
solution would not use a flag, but there's no problem using one.
A flag is a boolean variable which will be tested in the
while, and will be set in a conditional in the loop, when you
find something that makes you want to leave the loop.
The second issue is that you are using num without checking
that the input has succeeded. You must check after the >>
operator. The idiomatic way of checking (and the only thing
that should ever be used by someone not experienced in the
language) is to treat the stream as if it were a boolean:
dataFile2 >> num;
if ( dataFile2 ) {
// Input succeeded...
} else {
// Input failed for some reason, maybe end of file
}
Since all operations on a stream return a reference to the
stream, it is usual to merge the test and the input:
if ( dataFile2 >> num ) {
// succeeded
} else {
// failed
}
(Personally, I find the idea of modifying state in the condition
of an if or a while horrible. But this idiom is so
ubiquitous that you should probably use it, for the simple
reason that that's what everyone expects.)
In pedagogical environments, it's probably acceptable to
consider any failure to be end of file, and just move the test
up into the while (except, of course, that you've been asked
to use a flag). In other contexts, you'll want to take into
account the fact that the failure could be due to a syntax error
in the input—someone inserted "abc" into the file where
you were expecting a number. There are a number of ways of
handling this, all of which are beyond the scope of what you are
trying to do, but be aware that after you've detected failure,
you can interogate the stream to know why. In particular, if
dataFile2.eof() is true, then the failure was (probably) due
to you having read all of the data, and everything is fine. (In
other words, failure to read a data is not necessarily an error.
It can be simply end of file.)
You don't seem to be using a flag variable, which could help in this case. Something like this should fix it:
sum = 0;
bool sumUnder1000 = true; //Or the C++ equivalent, I'm a bit rusty
while(sumUnder1000)
{
if(!dataFile2.good()){
sumUnder1000 = false; //We've reached end of file or an error has occurred
return;
}
dataFile2 >> num;
sum = sum + num;
else if(sum > 1000){
sum = sum - num;
sumUnder1000 = false;
}
}

Best practice for having two if statements from the same bool c++

I have an if statement that [obviously] only runs if the condition is true. After this if statement there is some code that should always run, after that is another if statement that should run under the same condition as the first.
The code in the middle is performing an operation using a particular element of a stack, the ifs on either side perform a push/pop on the stack before and after the operation respectively.
so the logic is something like this:
Do I need to push the stack? yes/no
perform operation on top of stack
Was the stack pushed? (if yes then pop)
items 1 and 3 are the same condition.
This is the code that I first wrote to do this in c++
#include <stdio.h>
#include <stdlib.h>
int somefunction(){
return rand() % 3 + 1; //return a random number from 1 to 3
}
int ret = 0;
//:::::::::::::::::::::::::::::::::::::::
// Option 1 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run = (ret = somefunction()) == 1; //if the return of the function is 1
run = (run || (ret == 2)); //or the return of the function is 2
if (run){ //execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 1 End
//:::::::::::::::::::::::::::::::::::::::
After writing this I thought that it might be more efficient to do this:
//:::::::::::::::::::::::::::::::::::::::
// Option 2 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run;
if (run=(((ret = somefunction()) == 1)||ret == 2)){ //if the return of the function is 1 or 2 then execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 2 End
//:::::::::::::::::::::::::::::::::::::::
I prefer the first method for readability as it is split into several lines whereas the second has two assignments (=) and two comparisons (==) in the same line.
I want to know if it is better to use the second method (for reasons of efficiency or executable size) or if there is a better method than both.
Before anyone says it will only make an almost immeasurable difference, this is in a huge loop that has to run many thousands of times within 1/50 of a second so I would like to save as much time as possible.
Performance should not be your concern: the modern compilers are usually smart enough to optimize the code in any case. The results will be the same if the code is doing essentially the same thing.
So you should prefer the variant which is more readable (and therefore better maintainable).
I would write something like that:
ret = somefunction();
// I don't know what is the semantics of ret == 1, so let's imagine some
bool operationIsPush = (ret == 1);
bool operationIsOnTop = (ret == 2);
if (operationIsPush || operationIsOnTop)
{
//conditional code
}
if (operationIsPush)
{
//more conditional code
}
//unconditional code
if (operationIsPush || operationIsOnTop)
{
// ...
}
I believe there will be no difference in the performance here. The first reason is that your compiler will probably optimize the code in each case. The second is that you just change the place where operations take place (like "I do A->B->C or A->C->B"), not the amount of operations, so it's always the same amount of computing (1 function call, a couple of == and so on).
However consider that this
(run=(((ret = somefunction()) == 1)||ret == 2))
is pretty hard to read.
Correctness is more important than whether you fold two operations assigning a bool into one (which the compiler will probably do anyway).
For pushing/popping a stack, you should use a scopeguard (original article here). This will ensure that if something throws in the "unconditional bit", which you never really know for sure, then it still runs correctly. Otherwise you get funny a surprise (stack off by one, or overflowing).
if theres a situation that you can split "if-else" to distinct huge loops, it will be faster
rather than
loop { if_1 {some work} if_2 {some other work} }
you can
if_1 { loop {work }} if_2 {loop{same work}}
even more extremely, if you can split the most inner "if" sentences, you can have 10-20(dpending on your situation) distinct huge loops that runs x2 x3 faster (if it is slow bacause of "if")

Infinite Loops and Early Return Statements

I have a simple console application that outputs a menu and waits for user input. After performing the appropriate action, the entire process repeats. The program exits when a specific string is entered. This is implemented with an infinite loop and an early return statement:
int main()
{
while (true)
{
OutputMenu();
string UserChoice;
cin >> UserChoice;
// ...
if (UserChoice == "exit") return 0;
}
}
According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement. He suggests something like the following:
int main()
{
bool ShouldExit = false;
while (!ShouldExit)
{
OutputMenu();
string UserChoice;
cin >> UserChoice;
// ...
if (UserChoice == "exit") ShouldExit = true;
}
return 0;
}
Is it really a bad idea to use an infinite loop and an early return statement?
If so, is there a technical reason or is it just bad practice?
This might be one of those rare cases where do...while is appropriate. I avoid adding extra boolean state variables unless they genuinely make the code clearer.
int main()
{
string UserChoice;
do
{
OutputMenu();
cin >> UserChoice;
// ...
} while (UserChoice != "exit");
}
However, for a user input loop I would usually make a function that returns whether or not the input was successful. As it stands the code could easily end in an infinite loop if cin closes.
E.g.
bool GetNonExitInput( std::istream& in, std::string& s )
{
OutputMenu();
in >> s;
return in.good() && s != "exit";
}
int main()
{
std::string UserChoice;
while (GetNonExitInput(std::cin, UserChoice))
{
// ...
}
}
Really either is fine, but you need to do what your professor wants. You'll find it is the same in industry as well. Some companies may have a coding standard that dictates curly braces go on a new line, while others want them to start on the line that begins the block. There is no real reason to prefer one over the other, so it is best to just go with what the lead wants.
The only difference between these two approaches is that in the second approach you can still do something after you exit the while loop, while in the first approach, you're returning from the function itself; you can do nothing after the while.
However, I would suggest this simple code : instead of maintaining a variable, you can also use break like this:
while (true)
{
//your code
if (UserChoice == "exit")
break;
//your code
}
The variable ShouldExit is not needed anymore!
Depends on the language. If you're writing in C, then the "one entry, one exit" philosophy makes sense -- you want one place where you're cleaning up resources used by a function so that you don't have a chance of forgetting later. If you're in C++, then you should be using RAII for cleanup anyway, in which case I completely disagree with your teacher. Use returns as needed in order to make the code as clear as possible.
(Though I would use for (;;) instead of while (true) in C++ to generate the infinite loop)
With the controlled variable you would be able to handle exit conditions (code after the while) before exiting the function.
In my opinion both ways are fine, but the second one is "prettier".
In programing it is important to write the code in the easiest way you can think of, and make it simple for other programmers to understand your code if you'll be replaced or for any other reason.
There is no complexity issue involved with your two codes so they are both fine as I said, but the think I don't like about the first code is the use of 'return' statment without any real need of 'return' statment here.
There is another way writing this code, better then your way (in my opinion), but not better as your teacher's one.
int main()
{
bool ShouldExit = false;
while ( true )
{
OutputMenu();
string UserChoice;
cin >> UserChoice;
// ...
if (UserChoice == "exit") break;
}
}
Another main reason why I don't like your first code and my code above is because of the use of infinite loop, when you make yourself used to infinite loops it is just a matter of time until you will make your more complicated programs with major bugs in it.
Again - all of the things I wrote are in my opinion only and not gospel truth.
Rotem
Technically, there's not much in it, as long as there's no code you're skipping over via the use of the return.
However, your teacher's suggestion is more readable, if only because of the obvious meaning of "ShouldExit".
I think what your teacher means that the exit condition can easily maintained. This because of code cleanup after the while loop. If you will do a hard return then everything after the while loop will not be executed. This can prevented by using a break instead of return.
int main()
{
//create a file
while (true)
{
OutputMenu();
string UserChoice;
cin >> UserChoice;
//write UserChoice to file
// ...
if (UserChoice == "exit") return 0;
}
//close file
}
//close file will then not be executed!
The break statement is specifically for exiting loops.
I would usually prefer what your teacher suggested, simply because it's easier to read and understand what are the conditions to stop the loop.
If you have an infinite loop with a return statement it's a little bit more difficult for someone who didn't write the code to go through the code and figure out when the program will hit a return statement.
Also I usually don't like early returns in general because it's easy for someone maintaining the code to introduce bugs, for example:
int main()
{
// code added by some other programmer:
importantInitialization();
while (true)
{
OutputMenu();
// code added by some other programmer:
Something *st = new Something();
string UserChoice;
cin >> UserChoice;
// ...
if (UserChoice == "a") runA();
else if (UserChoice == "b") runB();
else if (UserChoice == "c") runC();
else if (UserChoice == "d") runD();
else if (UserChoice == "exit") return 0;
else if (UserChoice == "help") showHelp();
// code added by some other programmer:
delete st; // this would not run on the last loop
}
// code added by some other programmer:
importantCleanUp(); // this would never run
}
of course that in this particular case it's easy to see the problems, but when maintaining a more complicated function you can see how an early return statement might make it even more prone to lack-of-attention bugs like this.
I think the while(true) with break is best for a few reasons. Introducing a variable to store the exit condition is error prone, more variables means more can go wrong. Also the break statement is meant specifically for breaking out of loops. Lastly, contrary to for(;;), while(true) is clean, readable, and concise, where for(;;) is trying to be clever for no good reason.
For an added point, to enhance readability and comprehension put the exit condition(s) nearest to the top of the loop as possible:
while (true) {
OutputMenu();
string UserChoice;
cin >> UserChoice;
if (UserChoice == "exit")
break;
// process other options here
}
A routine which uses a local flag is, in terms of state analysis, equivalent to the same code, copied out twice, with one copy corresponding to the flag being true, and the other copy being equivalent to the flag being false, and any code which changes the state of the flag jumping between them. If there are n flags, the equivalent would be 2^n copies of the code (though if some flags are mutually exclusive, some of those may be unreachable and irrelevant).
While there are certainly times that flags are the most practical way to do things, they add complexity to the code. When the complexity is really necessary, flags may be the cleanest way to provide it. When there's a clean and practical way to write code which avoids the flags, one should do so. There are certainly times when it may be unclear whether it's better to use or avoid a flag (e.g.
flag = condition_which_must_be_tested_here();
action_which_will_disturb_the_condition();
if (flag)
do_something();
else
do_something_else();
versus
if (condition_which_must_be_tested_here())
{
action_which_will_disturb_the_condition();
do_something();
}
else
{
action_which_will_disturb_the_condition();
do_something_else();
}
but in cases where no code can be written without a flag and without having to duplicate anything, such a version is generally preferable.
I'm philosophically opposed to while(true). It means "loop forever" and you never really want to loop forever.
On the other hand I'm also philosophically opposed to boolean variables that merely record state that can be found out in other ways. There's a bug in waiting in that it may not always be correctly synchronised with the state it is supposed to reflect. In this case, I'd prefer code like:
int main()
{
string UserChoice = "not started"; // or empty string
while (UserChoice != "exit")
{
OutputMenu();
string UserChoice;
cin >> UserChoice;
// ...
}
return 0;
}

Why use if-else if in C++?

Why would you use if-else statements if you can make another if statement?
Example with multiple ifs:
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()
Example with else-if:
input = getInputFromUser()
if input is "Hello"
greet()
else if input is "Bye"
sayGoodbye()
else if input is "Hey"
sayHi()
If you have non-exclusive conditions:
if(a < 100)
{...}
else if (a < 200)
{...}
else if (a < 300)
....
this is very different from the same code without the "else"s...
It's also more performant.
In your first example, every if will be checked, even if input is "Hello". So you have all three checks.
In your second example, execution will stop once it found a branch, so if the user types "Hello" it will be only one check instead of three.
The difference may not be much in your simple example, but imagine that you're executing a potentially expensive function and you might see the difference.
you mean like this:
if (a == true && b == false && c == 1 && d == 0) {
// run if true
}
if (a == false || b == true || c != 1 || d != 0) {
// else
}
An else-statement would be much clearer and easier to maintain.
If you need to chose exactly one action from given set of actions, depending on some conditions, the natural and most clear choice is either switch (don't forget to break after each branch) or combination of if and else. When I write
if (conditon1)
{
action1();
}
else if (condition2)
{
action2();
}
else if (conditon3)
{
action3();
}
.
.
.
else {
action_n();
}
it is clear to the reader that exactly one of actions is to be performed. And there is no possibility that because of mistake in conditions more than one action is performed.
Following your same example if we use sequence of if conditions, whatever the input is it will run all 3 conditions. Replacing sequence of if with if-else conditions will run only first condition in best case whereas all 3 in worst case.
So conclude with that if-else will save our running time in most cases, therefore using if-else is preferred over using sequence of if conditions.
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()