Fixing a small error in the output using arrays in C

I am currently working on a project that, when set to a main function that calls another confab () function, outputs serious characters. The question concerns a particular race. They choose an integer nRows between 2 and half the length of the message, for example. a message of length 11 will allow nRows values ​​in the range 2 to 5. The message is then written to the grid columns, one character in each grid cell, nRows in each column, until all message characters have been used. This can result in the last column being only partially filled. Then the message is read line by line.

For example, the message "Do not wait for the last day before starting" with nRows of 3 will return:

D'wtnlhltabo ai.ota t ea yersrnn iuit sd fettg

      

I wrote some code that does this quite efficiently, however I was provided with a test case that doesn't seem to work.

 char buffer[8] = {'*','*','*','*','*','*','*','*',};
confab("ABCDEF.", 3, buffer);
printf("%s\n", buffer);

      

This example and the conclusion it should give is:

AD.BECF

      

However, my code returns:

AD.BECF*

      

Because of the extra *, the character is not replaced in the outText buffer. I've tried a lot of things like removing that extra *, or re-initializing outText to the same length as inText (inside the code, since the main case is not allowed to edit), however nothing has changed so far.

I was wondering if there would be a quick edit that I could apply to my code that would make this change, as I can't seem to find a way to separate the main input, which is not allowed.

My code looks like this:

/*
 * Confabulons.c
 * A program to encode for the Confabulons
 *
 * August 8th 2015
 */

#include <stdio.h>
#include <string.h>

//A simple function confab which given input text, and a number
//of rows, returns a phrase in the Confabulons encoding scheme.

void confab(const char inText[], int nRows, char outText[])
{
    int count = 0;
    int i = 0;
    int z = 0;
    int len = strlen(inText);

    while (z < nRows)
    {
        while (((int)inText[count] > 0) && (count < len))
        {
            outText[i] = inText[count]; 
            i ++;
            count = count + nRows;
        }
        z ++;
        count = z;
    }
}

      

+3


source to share


2 answers


At the end of the function add the line:



outText[i] = '\0';

      

+4


source


You need to check the length of the outText string, try:



void confab(const char inText[], int nRows, char outText[])
{
    int count = 0;
    int i = 0;
    int z = 0;
    int len = strlen(inText);
    int lenOut = strlen(outText);

    while (z < nRows)
    {
        while (((int)inText[count] > 0) && (count < len))
        {
            outText[i] = inText[count]; 
            i ++;
            count = count + nRows;
        }
        z ++;
        count = z;
    }
    if (i < lenOut) {
        outText[i] = '\0';
    }
}

      

+1


source







All Articles