Featured post
c - Convert white space to tabs -
i decided learn c, started going through k&r, got stuck on problem 21 in chapter 1. supposed write program, given string without tabs , tabwidth, converts white space equivalent spacing using tabs , white space.
so far, i've got this:
void entab (char from[], char to[], int length, int tabwidth) { int i, j, tabpos, flag, count; j = tabpos = flag = count = 0; (i = 0; from[i] != '\0' && j < length - count - 2; i++) { if (from[i] == ' ') { // if see space, set flag true , increment // whitespace counter. don't add characters until reach // next tabstop. count++; tabpos = (tabpos + 1) % tabwidth; flag = 1; if (count >= tabwidth - tabpos) { to[j] = '\t'; j++; count = count - tabwidth + tabpos; tabpos = 0; } } else { if (flag == 1) { // if see other space , flag true, // there weren't enough spaces reach tabstop. add count // spaces string. flag = 0; tabpos = (tabpos + count + 1) % tabwidth; while (count > 0) { to[j] = ' '; j++; count--; } } else { tabpos = (tabpos + 1) % tabwidth; } count = 0; to[j] = from[i]; j++; } } to[j] = '\0'; return; }
which, unfortunaly, seems produce larger spacing it's supposed to. ideas screwed up?
ps i've looked @ other solutions online , understand there better approach problem, fix error in mine well.
edit: setting tabwidth=4 , using:
foobar foo bar foo bar foo bar
as input, get:
/t/tfoobar /t/t/t/tfoo bar/t/t/t foo bar /t/tfoo/t/t bar
as output, while correct output be:
/tfoobar /t/tfoo/t bar/t/t foo bar /tfoo/t/tbar
if (count >= tabwidth - tabpos)
this starts outputting tabs soon. consider input string:
"aa "
with 8 tabwidth. character 5 (i 4, count 3) when tabpos becomes 5, therefore triggering condition. don't want output tabs before variable reaches tabwidth.
i won't fix code either. instead of making general statements "refactor code" 21st century way of saying "rewrite code", can point out 1 obvious mistake. don't need tabpos variable. use (i % tabwidth). here on things should start falling place.
- Get link
- X
- Other Apps
Comments
Post a Comment