I'm doing some exercises from "C Programming Language" and can't figure out what is going on to give me certain output. Not really a roadblock because I got the output I wanted, but I don't understand why changing a certain piece of my code actually gave me the output I wanted. Was just looking for an explanation.
Here is the code that works the way I want it to. The part I am not understanding is the s[++i] = ' ';
in the 'k' for loop. Before I used s[++i]
, I used:
s[i] = ' ';
++i;
Which would only put 1 space in the array, no matter how many times that k loop ran.
Then, just for testing, I placed ++i;
above s[i] = ' ';
and not a single space was included in my output.
#include <stdio.h>
#define MAXLINE 1000
#define TABSTOP 5
/* Write a program "detab" that replaces tabs in the input with a proper
number of blanks to space to the next tab stop. Assume a fixed set of tab
stops, say every n columnns. Should n be a variable or a synbolic parameter? */
int main() {
char c;
int i, j;
int modTabStop, numTabs, k;
char s[MAXLINE];
i = 0;
while((c = getchar()) != EOF) {
if(c == '\t') {
modTabStop = i % TABSTOP;
numTabs = TABSTOP - modTabStop;
for(k = 0;k <= numTabs; ++k)
s[++i] = ' ';
}
else if(c == '\n') {
;
}
else {
s[i] = c;
++i;
}
}
for(j = 0;j <= i;++j)
printf("%c", s[j]);
return 0;
}
I'm just wondering why s[++i]
worked and none of the others did. My expected output is defined in the comment above the main function. But just for clarification, I was using the test string "the(tab)dog". When it works correctly, only 2 spaces should be placed in place of the tab in between "the" and "dog" because my tab stop is 5 and "the" is three letters long ("the(space)(space)dog"). If I put ++i;
after s[i] = ' '
, then I get a single space in between ("the(space)dog"). And if I place it before, I get no spaces ("thedog").
I just want to make sure I understand all this fully before moving on. Thanks guys!