Question

I am working my through K&R and i am a bit mythed about the output of my program, when tab is pressed instead inserting a tab into the char array line, an if statement is used to insert 8 blank chars; however when i press enter instead of getting the desired output, i get my word separated by newlines instead of blanks or spaces. Question 1.21 for the curious

    /*replaces tabs from input with equal number of spaces*/
#include <stdio.h>
#define MAXLINE 1000
int getliner(int maxlen, char line[]);
int main(){
    char line[MAXLINE];
    int len=0;
    while((len=getliner(MAXLINE, line))>0){
        printf("%s\n", line);
        len=0;
    }
    return 0;
}
/*getline: puts input in arr, returns lenght*/
int getliner(int max, char s[]){
    int i, j;
    char c;

    for(i=0;i<max-1 && (c=getchar())!=EOF && c!='\n' && c!='\t';++i)
        s[i]=c;
    if((c=='\t')){
        for(j=(i+8);i<j;i++)
            s[i]=' ';
        s[i]='\0';
    }
    if((c=='\n')){
        s[i]='\n';
        ++i;
    }
    s[i]='\0';
    return i;

}

an example of the output

dom     dom   <-- this is the input
dom            <-- here is the output
dom

from what i can tell my code takes care of the newline char, not only that the newline doesnt appear until after the final 'm' of the input. it seems to me that when tab is pressed a '\n' char is inserted to the line, but my code add 8 blanks.

Was it helpful?

Solution

Your string already contains a newline (that you copied from the input), but you're printing:

    printf("%s\n", line);

Which adds another newline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top