954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Character Arrays

Im trying to create a simple RLC program. Im n ot sure the best way about it, but im trying to to use to 20 character arrays. One to read in the characters to be compressed (buffer) and the other is used to as a check. Either way, the buffer[20] reads in from a file and is fine, but other array (outputs[20]) does not read anything in, so when i set the first element of outputs[0] = buffer[0], i get the first letter of buffer, followed by a gibberish, which throws off all calculations. Code is below:

int Readchar(ifstream& fileread)
{
    char buffer[20];
    char temp;
    int space, count, length;
    count = 0;
    cout << fileread.peek() << endl;
    while (fileread.peek() != EOF)
    {
         fileread >> buffer;
         Checkbuffer(buffer);
         count ++;  
    }
    return 0;
}


int Checkbuffer(char buffer[])
{
    char outputs[20];
    int k, length, count, adj;
    adj = 0;
    count = 0;
    length = strlen(buffer);
    outputs[0] = buffer[0];
    cout << outputs;   
    for (k = 1; k <= length; k++)
    {
        if (buffer[k] == outputs[k-1])
        {
            outputs[k] = buffer[k];
        }
        else
        {
            Outputstring(outputs,k);
        }             
    }
    return 0;
}


If anyone can suggest how to empty outputs[20] so it contains nothing, it would be appreciated.
Regards
Kevin

kdw3
Newbie Poster
15 posts since Oct 2005
Reputation Points: 10
Solved Threads: 0
 

cout << buffer -- buffer needs to be a null-terminated character array. when you defined buffer you did not initialize it to anything, that means it contains random characters and the buffer may or may not contain a null-terminating 0. So cout just keeps displaying characters searching all memory for the first 0, which may be considerably beyond the end of the buffer.

To avoid that problem, declare buffer like this

char buffer[20]  = 0;

That will fill the buffer with all 0s.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You