Question: Can someone explain to me what the if( pos > 0) putchar('\n'); does and why it does that? Why does it check if the position is greater than 0, and if it is, put a newline character?
Write a program to fold long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something ntelligent with very long lines, and if there are no blanks or tabs before the specified column.
Solution
/* fold, to fold long lines after a specified Column */ #include #define MAXCOL 50 #define TABVAL 8 char line[MAXCOL]; int expandtab(int pos); int printline(int pos); int getblank(int pos); int newposition(int pos); int main(void) { int pos,c; pos = 0; while((c=getchar())!=EOF) { line[pos] = c; if( c == '\t') pos = expandtab(pos); if( c == '\n') { printline(pos); pos = 0; } else if( ++pos >= MAXCOL ) { pos = getblank(pos); printline(pos); pos = newposition(pos); } } return 0; } int expandtab(int pos) { line[pos] = ' '; for(++pos; (pos < MAXCOL)&&((pos % TABVAL)!= 0); ++pos) line[pos] = ' '; if( pos >= MAXCOL) { printline(pos); return 0; } else return pos; } int printline(int pos) { int i; for(i = 0; i < pos; ++i) putchar(line[i]); if( pos > 0) putchar('\n'); } int getblank(int pos) { if( pos > 0) while( line[pos] != ' ') --pos; if(pos == 0) return MAXCOL; else return pos + 1; } int newposition( int pos) { int i,j; if(pos <= 0 || pos >= MAXCOL) return 0; else { i = 0; for(j=pos;j < MAXCOL; ++j,++i) line[i] = line[j]; } return i; }
Please find the answer to your question:
what the if( pos > 0) putchar('\n'); does and why it does that?
In the function printline it takes input as the position till the characters arr read for 1 column. Now when it prints the character of the one line first it prints the character to the console using the first for loop:
for(i = 0; i < pos; ++i) putchar(line[i]);
then in the next line it checks if that line actually contains a character or not because if it contains the characters then the value of pos must be greater then 0 and that means that this line needs to end. So it's giving input as the
putchar('\n');
which print the new line to the console. "\n" is an escape sequence to print the new line on the console in the C language and many other languages. It indicates compiler to print the new line on the console whenever there is "\n"
Get Answers For Free
Most questions answered within 1 hours.