[Exercise] Exercise 5-11. Modify the program entab and detab page 118

User avatar

Topic author
BJT
Site Admin
Site Admin
Posts: 141
Joined: Thu Apr 20, 2017 4:43 pm
Instruction: University Student
Gender:
Age: 27
Venezuela

Exercise 5-11. Modify the program entab and detab page 118

Post by BJT » Sat May 06, 2017 1:54 am

Exercise 5-11. Modify the program entab and detab (written as exercises in Chapter 1) to accept a list of tab stops as arguments. Use the default tab settings if there are no arguments.


entab
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. int main(int argc, char * argv[])
  6. {
  7.     int tab;
  8.     if (argc>1&&isdigit(*(*++argv)))
  9.         tab=atoi(*argv);
  10.     else
  11.         tab=5;
  12.  
  13.     int c;
  14.     while((c=getchar())!=EOF)
  15.     {
  16.         if(c=='\t')
  17.             for(int i=0;i<tab;i++)
  18.                 putchar(' ');
  19.         else
  20.             putchar(c);
  21.     }
  22.  
  23.     return 0;
  24. }

input 1

Code: Select all

./c 20
Hello	world
output 1

Code: Select all

Hello                    world
input 2

Code: Select all

./c
Hello	world
output 2

Code: Select all

Hello     world
detab
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. int main(int argc, char * argv[])
  6. {
  7.     int tab;
  8.     if (argc>1&&isdigit(*(*++argv)))
  9.         tab=atoi(*argv);
  10.     else
  11.         tab=5;
  12.  
  13.     int c,h;
  14.     int multi=0;
  15.     long counter=0;
  16.  
  17.     while((c=getchar())!=EOF)
  18.     {
  19.         if(c==' ')
  20.             ++counter;
  21.         if((counter>0)&&(c!=' '))
  22.         {
  23.             if(counter<tab)
  24.             {
  25.                 for(h=0; h<counter;h++)
  26.                     putchar(' ');
  27.             }
  28.             if(counter>=tab)
  29.             {
  30.                 for(h=tab; h<counter;h=h+tab,multi++)
  31.                     putchar('\t');
  32.                 for(counter=counter-multi*tab;counter>0;counter--)
  33.                     putchar(' ');
  34.             }
  35.             counter=0,multi=0;
  36.         }
  37.         if(c!=' ')
  38.             putchar(c);
  39.     }
  40.  
  41.     return 0;
  42. }

input 1

Code: Select all

 ./c 6
Hello        world			     again
output 1

Code: Select all

Hello	  world			     again
input 2

Code: Select all

./c
Hello        world			     again
output 2

Code: Select all

Hello	   world			     again
word count: 257

Link:
BBcode:
HTML:
Hide post links
Show post links

Who is online

Users browsing this forum: No registered users and 1 guest