2

Trying to implement detab function which is described in K&R book http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_20 an faced a problem: when outputting a replaced string there's a question mark in the end of the output. Why?

#include <stdio.h>
#define MAXLINE 9999

void get_text(char output[]);
void detab(char input[], char output[], int tab_size);

int main()
{
    char input[MAXLINE];
    char final[MAXLINE];
    get_text(input);
    detab(input, final, 4);
    for (int i = 0; final[i] != '\0'; ++i)
    {
        putchar(final[i]);
    }
    putchar('\n');
    return 0;
}

void get_text(char output[])
{
    int c;
    int i = 0;
    for (i = 0; i < MAXLINE && (c = getchar()) != EOF; ++i)
    {
        output[i] = c;
    }
    output[i + 1] = '\0';
}

void detab(char input[], char output[], int tab_size)
{
    int c = 0;
    int r = 0;
    for (int i = 0; input[i] != '\0'; ++i)
    {
        c = input[i];
        if(c == '\t')
        {
            for (int t = 0; t < tab_size; ++t)
            {
                output[r] = '.';
                r++;
            }
        }
        else
        {
            output[r] = c;
            r++;
        }
    }
    output[r] = '\0';
}

And here is the output when I'm passing the file with following content 'asdasdads tasdasdasdasdasd sadasdasd':
asdasdads....tasdasdasdasdasd....sadasdasd? (? at the end). Why there is a question mark at the end?

Dima Knivets
  • 2,418
  • 7
  • 28
  • 40

2 Answers2

3
output[i + 1] = '\0';

You don't need to add 1 here, it was already done in the loop. (First i is incremented and then i < MAXLINE && (c = getchar()) != EOF is tested, so i is one higher than in the last loop iteration already)

2

I'd guess that's in place of an unprintable character. The characters in final aren't initialized to anything in particular, and you're leaving a gap at the end of the detabbed string when you say:

output[i + 1] = '\0';

output[i], one past the output text, is still uninitialized.

You want:

output[i] = '\0';
Paul Roub
  • 36,322
  • 27
  • 84
  • 93