Home > Net >  Problems whith assigning/printing characters in an array in a constructor throrugh a loop
Problems whith assigning/printing characters in an array in a constructor throrugh a loop

Time:10-10

I'm trying to assign characters to the hex[] array through a simple for loop in the constructor but something isn't working. It simply doesn't print anything. If I use the commented code on the other hand, it prints fine (obviously after removing the assigning loop).

#define DIM 6
#include<iostream>
using namespace std;

class hexnum
{
    private:
        char hex[DIM];
    
    public:
        hexnum();
        void print();
};

hexnum::hexnum()
{
    /*
    hex[0] = '0';
    hex[1] = '0';
    hex[2] = '0';
    hex[3] = '0';
    hex[4] = '0';
    hex[5] = '0';
    */  
    
    for(int i = 0; i<DIM; i  )
    {
        hex[i] = '0';
    }   
}

void hexnum::print()
{
    for(int i; i<DIM; i  )
    {
        cout<<hex[i];
    }
    return;
}

int main ()
{
    hexnum n1;
    n1.print();
}

I cannot for the life of me figure out why! Am I missing something simple or is there something I should know? I'm still very much a coding beginner and barely started to touch on classes.

CodePudding user response:

void hexnum::print()
{
    for(int i=0; i<DIM; i  )
    {
        cout<<hex[i];
    }
    return;
}

initialize i=0 so that it can iterate from starting index

  • Related