Snerd
Snerd

Reputation: 1553

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

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.

Upvotes: 1

Views: 1351

Answers (2)

felipemaia
felipemaia

Reputation: 3571

You could read an int and parse it this way:

int number = 0;

cin >> number;
int i = 0;
while(i < MAX)
{
    if(number > 0)
    {
        zelda[i] = number % 10; // or you can switch to zelda[MAX-(i+1)]
        number = number/10;
    else
    {
        zelda[i] = 0;
    }
    i++;
}

EDIT:
Note that this conversion is in little endian format, meaning that if you type the int '100', zelday will be filled with '001'.

EDIT2:
If you want to get it from a string instead, do this, assuming zelda has the same size of str:

string str ("111000");
int i;
for (i=0; i < str.length(); i++)
{
    zelda[i] = (str[i] - '0');
}

Reason why this works:
The numbers represented in a char list are sequential (int this case ASCII), that is, the number zero is represented as 48, the number one is represented by 49, and so on. So when you subtract the representation of the '0', you get the actual number.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477100

To read data, see this related question (and replace the file stream by std::cin).

To convert, you can do something simple:

unsigned int convert(const std::string & s)
{
  // maybe check that s.size() <= CHAR_BIT * sizeof(unsigned int)

  unsigned int result = 0;

  for (std::string::const_reverse_iterator rit = s.rbegin(), rend = s.rend(); rit != rend; ++rit)
  {
    result *= 2;

    if (*rit == '1') ++result;

    else if (*rit != '0') { /*error!*/ return -1; }
  }

  return result;
}

Upvotes: 2

Related Questions