1
\$\begingroup\$

I wrote a program that replaces tabs with spaces. First, I defined a maximum length of an input string in the constant MAX_LIMIT. Next, I declared the procedure detab that takes two arguments: an input string and a maximum length. In the procedure I read characters until encountering EOF. I'm replacing tabs with four spaces and I'm checking if index is equal to limit, and if yes, then I break the loop. Finally, I created a str character array. I called on it the detab procedure and I printed out the value of str in main.

main.c

#include <stdio.h>
#define MAX_LIMIT 1000
void detab(char str[], int limit);
int main(void) {
 char str[MAX_LIMIT];
 detab(str, MAX_LIMIT);
 printf("%s", str);
 return 0;
}
void detab(char str[], int limit) {
 char current;
 int index = 0;
 int stop = 0;
 while ((current = getchar()) != EOF) {
 if (stop) {
 break;
 }
 if (current == '\t') {
 for (int i = 0; i < 4 && !stop; i++) {
 if (index == limit) {
 stop = 1;
 } else {
 str[index++] = ' ';
 }
 }
 } else {
 str[index++] = current;
 }
 }
}

How can I improve this program? Is it an optimal solution of this problem?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 23, 2017 at 22:14
\$\endgroup\$
2
  • \$\begingroup\$ Possible duplicate of K&R 1-20 Converting tabs to spaces using idiomatic C \$\endgroup\$ Commented Jun 24, 2017 at 4:19
  • \$\begingroup\$ @tinstaafl A question is not a duplicate here if it solves the same problem as code in some other question. And the code seems sufficiently different not to be a direct copy. \$\endgroup\$ Commented Jun 24, 2017 at 8:58

1 Answer 1

3
\$\begingroup\$
  • First of all, it is not exactly doing what is expected of detab. The visual appearance of the detabbed text shall remain the same. You need to insert as many spaces as required to reach the next tab stop, not necessarily 4 of them.

    For example, a string ab\tc should become

    ab c
    

    (2 spaces inserted) whereas your code produces

    ab c
    
  • detab does not zero-terminate the string. It is an (un)lucky coincidence that the code produces meaningful output.

  • The limit condition is only tested during the tab expansion. A long sequence of ordinary characters will overrun the buffer.

answered Jun 23, 2017 at 23:16
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.