HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Entabbing a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
entabbingstringstackoverflow

Problem

I am trying to finish the K&R book on C. Below is an exercise which took a long time to finish. I would like some feedback on optimization or any blatant issues with the code.


Exercise 1-21


Write a program entab that replaces strings of blanks by
the minimum number of tabs and blanks to achieve the same spacing.
Assume a fixed number of tabstops.

#include
#define TABSTOP   8
#define TABCHAR   '\t'
#define SPACECHAR '#'

void entab(char input[]);
void printchars(char c, int times);
void printruler();

int main(int argc, char const *argv[])
{
  /*char input[] = "this         is an   aw some piec  of code.\n";*/
  char input[] = "this         is an   aw some piec  of code.\nright o            bro!\n";
  printruler();
  printf("%s", input);
  entab(input);
  printruler();
  return 0;
}

void entab(char input[])
{
  int c;

  for (size_t i = 0, pos = 1, spaces = 0; (c = input[i]) != '\0'; ++i){

    if (c == ' '){
      //else increment the number of spaces
      ++spaces;

      //if we have spaces equal to 1 tab width print the tab
      if(pos % TABSTOP == 0){
        putchar('\t');
        spaces = 0;
      }

    } else{
      //if the current character is not a space print the spaces and the character
      printchars(SPACECHAR, spaces);
      putchar(c);
      spaces = 0;
    }

    if( c == '\n' )
      pos = 1;
    else
      pos += 1;

  }
}

void printchars(char c, int times){
  for (size_t i = 0; i < times; ++i){
    putchar(c);
  }
}

void printruler(){
  for (int i = 1; i < 100; ++i){
    if(i%TABSTOP == 0)
      putchar('|');
    else
      putchar('_');
  }
  putchar('\n');
}

Solution

Be careful to keep your types consistent. Here's your printchars() method:

void printchars(char c, int times){
  for (size_t i = 0; i < times; ++i){
    putchar(c);
  }
}


You're expecting times to be passed as an int, but then you treat it like a size_t in the for loop. You should choose one type and stick with it.

Personally I think you should be using int rather than size_t to ensure your that types reflect their usage and make your code somewhat self-documenting.

Code Snippets

void printchars(char c, int times){
  for (size_t i = 0; i < times; ++i){
    putchar(c);
  }
}

Context

StackExchange Code Review Q#9000, answer score: 3

Revisions (0)

No revisions yet.