#include #include // for atoi() #include // for strlen() // assume output width 80 bytes // assume no word ever longer than one output line int main(int argc, char *argv[]) { const unsigned outlength=81; char outline[outlength]; char *outptr; const unsigned wordlength=81; char word[wordlength]; char *wordptr; *(outptr=outline)=0; *(wordptr=word)=0; int wrapping=0; int more=1; while (more) { char c; cin.read(&c,1); if (cin.eof() || !cin.good()) more=0; if (!more || c == '\n') { // if word fits add it if (wordptr-word < outlength-(outptr-outline+1)) { strcat(outptr,word); outptr+=wordptr-word; *(wordptr=word)=0; } // purge the line regardless { cout << outline << '\n' << flush; *(outptr=outline)=0; wrapping=0; // allow spaces at line start } // if word did't fit, add it if it does now (it must) if (wordptr-word < outlength-(outptr-outline+1)) { strcat(outptr,word); outptr+=wordptr-word; *(wordptr=word)=0; } // if no more, and a line left, purge it finally if (!more && outptr-outline) { cout << outline << '\n' << flush; } } else if (c == ' ') { // cerr << "space:\n" << flush; // if word fits add it if (wordptr-word < outlength-(outptr-outline+1)) { // cerr << "space: adding word 1\n" << flush; strcat(outptr,word); outptr+=wordptr-word; *(wordptr=word)=0; // cerr << "space: line now=<" << outline // << ">\n" << flush; } // else purge the line else { cout << outline << '\n' << flush; *(outptr=outline)=0; wrapping=1; // disallow spaces at line start } // if word did't fit, add it if it does now (it must) if (wordptr-word < outlength-(outptr-outline+1)) { // cerr << "space: adding word 2\n" << flush; strcat(outptr,word); outptr+=wordptr-word; *(wordptr=word)=0; // cerr << "space: line now=<" << outline // << ">\n" << flush; } if (!wrapping || outptr-outline) { // cerr << "space: adding space\n" << flush; *outptr++=c; // overflow ??? *outptr=0; } } else { // if (wordptr-word >= wordlength) error; *wordptr++=c; *wordptr=0; // cerr << "char: word=<" << word << ">\n" << flush; } } return 0; }