fill an array with Int like a Char; C++, cin object

Posted by Duknov007 on Stack Overflow See other posts from Stack Overflow or by Duknov007
Published on 2011-11-25T01:26:36Z Indexed on 2011/11/25 1:51 UTC
Read the original article Hit count: 131

Filed under:

This is a pretty simple question; first time poster and long time looker.

Here is my binary to decimal converter I wrote:

#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 6;
int conv(int z[MAX], int l[6], int MAX);

int main()
{
    int zelda[MAX];
    const int d = 6;
    int link[d];

    cout << "Enter a binary number: \n";  
    int i = 0;
    while (i < MAX && (cin >> zelda[i]).get())  //input loop
    {
        ++i;
    }   

    cout << conv(zelda, link, MAX);

    cin.get();
    return  0;
}

int conv(int zelda[MAX], int link[6], int MAX)
{   
    int sum = 0;
    for (int t = 0; t < MAX; t++)
    {
        long int h, i;
        for (int h = 5, i = 0; h >= 0; --h, ++i)
            if (zelda[t] == 1)
                link[h] = pow(2.0, i);
            else
                link[h] = 0;
            sum += link[t]; 
    }
    return sum;
}

With the way the input loop is being handled, I have to press enter after each input of a number. I haven't added any error correction yet either (and some of my variables are vague), but would like to enter a binary say 111111 instead of 1 enter, 1 enter, 1 enter, etc to fill the array. I am open to any technique and other suggestions. Maybe input it as a string and convert it to an int?

I will keep researching. Thanks.

© Stack Overflow or respective owner

Related posts about c++