0

Suppose I want to compute the binary value of a series of numbers entered by a user but I don't want to set a limit to how many numbers the user can enter, so I do this in Python 3:

try:
    lst = list()
    while True:
        n = int(input("Enter the number: "))
        b = binary_of(n)                      // Function to find binary value
        lst.append(b)
except:
    print("The respective binary values are", '\n')
    print(lst)

In above code, the 'try' stops executing when the user enters a non-integer value and the program moves to 'except' to print the list and this is exactly what I want.

Can I do something similar in C++? Is there a 'try and except' version of C++ too??

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Shikhar
  • 37
  • 3
  • Yes, there is a *try and catch* version in `c++`. – Geno C Aug 29 '20 at 05:32
  • 1
    yes there is, it's called try and catch. However, this, to me, is bad programming practice. Instead of having an infinite loop, you can break when there is an error in the conversion to int for example. Also this is a general except (i.e. catch all errors). You don't know where the exception occured and what caused the exception. e.g. what if there was a problem in 'binary_of'? – Danyal Aug 29 '20 at 05:34
  • You can catch different types of errors so it's not a general problem but memory might be an issue. – Arundeep Chohan Aug 29 '20 at 05:38
  • 1
    @Danyal Why is this a bad practice? An error in `int` raises an exception. The exception breaks the loop. It is true, though, that `except` must be `except ValueError`. – DYZ Aug 29 '20 at 05:38
  • 1
    Does this answer your question? [Checking cin input stream produces an integer](https://stackoverflow.com/questions/18728754/checking-cin-input-stream-produces-an-integer) – kmdreko Aug 29 '20 at 05:53

1 Answers1

2

An exception is a problem that arises during the execution of a program. Allowing the user to stop giving more input is not a problem. Your logic should handle. There are multiple ways to do it.

Try..catch is always there for you.

One way could be parsing the input to check if the input is an int. If not, break the while.

Another way could be as shown below.

#include <iostream>
using namespace std;
int main() {
    int num;
    cin >> num;
    while(cin.fail()){
        //your logic goes here
        cin.clear();        
        cin.ignore(numeric_limits<int>::max(), '\n');
        cin >> num;
    };
    return 0;
}
Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57
  • A good addition would be that using try/except for control flow is an accepted idiom in Python at least in some situations. Doing the same with try/catch in C++ is heavily frowned upon. – besc Aug 29 '20 at 07:33
  • Or, more idiomatically, remove both `cin >> num;` statements and put the input in the `while`, like this: `while (cin >> num)`. +1. – Pete Becker Aug 29 '20 at 15:03