K & R C Programs Exercise 5-11.

K and R C, Solution to Exercise 5-11:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to modify the 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. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include<stdio.h>
#define MAXLINE 100
#define TABINC 8
#define YES 1
#define NO 0
void settab(int argc , char *argv[], char *tab);
void entab(char *tab);
void detab(char *tab);
int tabpos(int pos, char *tab);

main(int argc, char *argv[])
{
char tab[MAXLINE + 1];
settab(argc, argv, tab);
entab(tab);
settab(argc, argv, tab);
detab(tab);
return 0;
}

/*entab: replace strings of blanks with tabs and blanks */
void entab(char *tab)
{
int c, pos;
int nb = 0;
int nt = 0;
for(pos = 1;(c=getchar()) != EOF;pos++)

if(c == ' '){
if(tabpos(pos, tab) == NO)
++nb;
else{
nb = 0;
++nt;
}
}else {
for(;nt > 0;nt--)
putchar('t');
if (c == 't')
nb = 0;
else
for(;nb > 0;nb--)
putchar(' ');
putchar(c);
if(c == 'n')
pos = 0;
else if(c == 't')
while (tabpos(pos(pos, tab) != YES)
++pos;
}
}

/*detab:replace tab with blanks*/
void detab(char *tab)
{
int c,pos = 1;
while ((c = getchar()) != EOF)
if (c == 't') {
do
putchar(' ');
while (tabpos(pos++, tab) != YES);
}else if(c == 'n'){
putchar(c);
pos = 1;
}else{
putchar(c);
++pos;
}
}


//setab: set tab stops in array tab
void settab(int argc, char *argv[], char *tab)
{
int i, pos;
if (argc <= 1)
for(i = 1; i <= MAXLINE; i++)
if(i % TABINC == 0)
tab[i] = YES;
else tab[i] = NO;
else{
for(i = 1;i <= MAXLINE; i++)
tab[i] = NO;
while(--argc > 0){
pos = atoi(*++argv);
if(pos > 0 && pos <= MAXLINE)
tab[pos] = YES;
}
}
}


//tabpos: determine if pos is at a tab stop
int tabpos(int pos, char *tab)
{
if (pos > MAXLINE)
return YES;
else
return tab[pos];
}

Read more c programs 
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

Leave a Reply