-4

I am coding a program that converts a binary number into decimal number by doubling (link to wikihow article).

If the user input is something other than 1 or 0, then its not a binary number, under that circumstance I want the loop to "break" and say something like:

"Oops! Binary numbers have only 1 or 0".

If not "then" the loop should continue.

That is I want to code something like

for(int digits = 0; digits != digitsINbinNum; ++digits){
      if(a condition that checks if user input is anything else than 1 or 0){
         coût << ""Oops! Binary numbers have only 1 or 0" << endl; 
         break;
          }else{
        cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
      }
    }


Refer to the code given below for more info:

#include <iostream>
#include <iterator>

using namespace std;

int main(){
    int digitsINbinNum;
    cout << "If you don't mind. Please enter the number of digits in your binary number: ";
    cin >> digitsINbinNum;
    int binArray[digitsINbinNum];

    cout << "Enter the binary number: ";
    for(int digits = 0; digits != digitsINbinNum; ++digits){
        cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
    }

/*using the doubling method as found in wikihow.com*/
    int total = 0;
    for(int posiOFdigit = 0; posiOFdigit != sizeof(binNum[noOFdigits]); posiOFdigit++){
        total = total * 2 + binNum[posiOFdigit];
    }

    /*Printing the number*/
    cout << "Decimal form of ";
    for(int n = 0; n != noOFdigits; n++){
        cout << binNum[n];
    }
    cout << " is " << total;
    return 0;
}
Bulat
  • 720
  • 7
  • 15
  • How about using `std::vector` instead? – JVApen Jun 02 '19 at 13:57
  • 6
    `int binArray[digitsINbinNum];` isn't standard c++. – πάντα ῥεῖ Jun 02 '19 at 13:58
  • @JVApen I still haven't learnt that. But thx for the advice. – Jayed Yeameen Jun 02 '19 at 14:04
  • @πάνταῥεῖ I am using c++ 14 and in that Iine I mean that the size of the array will given by the user. – Jayed Yeameen Jun 02 '19 at 14:05
  • 4
    This didn't change for c++14. VLAs didn't make it into the standard. You're using a compiler extension at best. – πάντα ῥεῖ Jun 02 '19 at 14:06
  • In `c++` the size of an array must be a compile time constant. `c` allows VLAs but the `c++` standard does not. Some compilers that have implemented this for `c` allow it for `c++` however its better to just use `std::vector`. https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – drescherjm Jun 02 '19 at 14:28
  • You haven't learned about if statements or `break` yet? How are you learning C++? – eesiraed Jun 02 '19 at 18:28
  • I recommend reading a number as a string whenever you need to manipulate or examine the digits of the number. – Thomas Matthews Jun 02 '19 at 19:10
  • @AlexanderZhang Yes I have learned about them and I want to implement that in my code. But when try to do that the loop jus t gets skipped. – Jayed Yeameen Jun 02 '19 at 21:36
  • Then show your attempted implementation. Note that `cin >> binArray[digits];` will read the entire binary number as a decimal number (you said to input an int so that's what the computer did, it doesn't know you only want one digit). You need to read the number one character at a time by inputting into a char. – eesiraed Jun 02 '19 at 22:07
  • @AlexanderZhang Can you please clarify that by a code? Yes, I am taking one input at a time but it's an int and you're telling me to take it as char. I am a little confused there. – Jayed Yeameen Jun 02 '19 at 23:33
  • You're inputting into an int, so if you type in `1001` the whole thing will be read into `binArray[0]` as one thousand and one unless you're typing in `1 0 0 1`. The compiler doesn't know you only want the first digit. – eesiraed Jun 03 '19 at 02:52
  • @AlexanderZhang How can I tell the compiler that I want digits one by one not the whole number at once? – Jayed Yeameen Jun 03 '19 at 03:02
  • Read into a char variable. You can look up how to convert it into an int afterward. – eesiraed Jun 03 '19 at 03:03
  • @AlexanderZhang Can you please show me the whole coding of this, please? Or you can suggest edits in my code above. – Jayed Yeameen Jun 03 '19 at 03:11
  • Í wǒndèr whåt `coût` ïs. – L. F. Jun 03 '19 at 09:26
  • @L.F. I wrote this question on Android and used GBoard. My GBoard is configured to autocorrect anything in English and French. So while writing ```cout``` it autocorrected to French coût. I don't know what that means. So plz forgive me if it's something offensive. – Jayed Yeameen Jun 03 '19 at 10:36
  • @JayedYeameen Nope, a small typo has never been considered any offensive at all. It's just amusing ;-) – L. F. Jun 03 '19 at 10:37
  • @πάνταῥεῖ I am currently working on how to use vector here. – Jayed Yeameen Jun 12 '19 at 15:35

2 Answers2

0

The logic for converting a binary number into decimal number by the doubling method can be referred from the given link in the question.

Modifying the given code to keep it as close as possible to the question's reference code.

Note: As ISO C++ forbids variable length array, I am changing int binArray[digits] to int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);. This modification makes it an integer pointer and it gets the memory of required size allocated at runtime.

#include <iostream>

using namespace std;

int main(){
    int digitsINbinNum,
        /* variable to keep decimal conversion of given binary */
        decimal_val = 0;
    bool is_binary = true;
    cout << "If you don't mind. Please enter the number of digits in your binary number: ";
    cin >> digitsINbinNum;
    /*
     ISO C++ forbids variable length array,
     making it int pointer and allocating dynamic memory
    */
    int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);
    if (binArray == NULL)
    {
        cout << "Memory allocation failure" << endl;
        exit -1;
    }
    cout << "Enter the binary number: ";
    for(int digits = 0; digits != digitsINbinNum; ++digits){
        cin >> binArray[digits];
        /*<-----------Here's the part where I am trying to do that*/
        /* doubling method logic for conversion of given binary to decimal */
        if ((binArray[digits] == 0) ||
            (binArray[digits] == 1))
        {
            decimal_val = (decimal_val * 2) + binArray[digits];
        }
        else /* not a binary number */
        {
            is_binary = false;
            cout << "Oops! Binary numbers have only 1 or 0" << endl;
            break;
        }
    }

    /* if conversion is successful: print result */
    if (is_binary)
    {   
        cout << "Decimal Value for given binary is: " << decimal_val << endl;
    }
    if (binArray)
    {
        free(binArray);
    }
    return 0;
}
  • 1
    `warning: ISO C++ forbids variable length array ‘binArray’ [-Wvla]` – phinz Jun 02 '19 at 15:23
  • Would you edit this answer to explain how it is an answer to the question? Other users with the same problem appreciate this kind of material, as it helps them learn. – halfer Jun 02 '19 at 22:06
  • @phinz thanks for pointing that out. I have modified the answer to adopt ISO C++ standard. – Himanshu Kumar Jun 02 '19 at 23:26
  • 1
    @halfer I have added the explanation and inline comments in the code to make it more clear and self-explanatory. Thanks for pointing it out. – Himanshu Kumar Jun 02 '19 at 23:28
  • 1
    `malloc` in C++ without corresponding `free` is in a way even worse than VLAs. – eesiraed Jun 03 '19 at 02:58
  • @AlexanderZhang Modified to take care of it. Thanks! – Himanshu Kumar Jun 03 '19 at 03:49
  • It's better to avoid `malloc` completely and use `std::vector`. Even when done properly, doing manual memory management in C++ when it is unnecessary is bad practice. You could also use smart pointers. – eesiraed Jun 03 '19 at 05:36
-1

You don't need an array for this. Here is a simple solution:

#include <iostream>

int main(){
    int digitsINbinNum;
    std::cout << "If you don't mind. Please enter the number of digits in your binary number: ";
    std::cin >> digitsINbinNum;

    std::cout << "Enter the binary number: ";
    int ret = 0;
    for(int digits = 0; digits != digitsINbinNum; ++digits) {
        int bin;
        std::cin >> bin;
        if (bin == 1 || bin == 0) {
            ret = 2 * ret + bin;
        } else {
            std::cout << "Oops! Binary numbers have only 1 or 0" << std::endl;
            return -1;
        }
    }
    std::cout << ret << std::endl;

    return 0;
}
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • Can you please explain what the ```return -1``` is doing? – Jayed Yeameen Jun 03 '19 at 04:03
  • This still has the bug present in the OP's code, where `std::cin >> bin;` will read the entire number and interpret it as a decimal integer while you only want the first digit. [Proof](https://ideone.com/Blim5Z) – eesiraed Jun 03 '19 at 05:41
  • @JayedYeameen Returning a value other than 0 from `main` usually signals a runtime error. – eesiraed Jun 03 '19 at 05:42
  • @AlexanderZhang the user input has to be 0 or 1. So the user has to input each digit in one line followed by a newline. That is how I understand the question. – Thomas Sablik Jun 03 '19 at 07:25