So i understand what the getop function is and how it works, having trouble understanding the while loops that check for the integer and fraction part of the input and put them in the s array.
So i've been trying to write these same while loops in the standard way (expression in the parentheses then the statements below in the brackets).
so instead of the while loop being:
while(isdigit(s[++i] = c = getch())){
;
}
why cant it be:
while(isdigit(c = getch())){
s[++i] = c;
}
The full getop function:
int getop(char s[]){
int i, c;
while((s[0] = c = getch()) == ' ' || c == '\t'){
; //set s[0] to the first non space/tab char
}
s[1] = '\0'; //s[1] to \0
if(isdigit(c) == 0 && c != '.' && c != '-'){
return c; //if not a digit or . then return(must be a +,-,/,*)
}
i = 0;
if(isdigit(c)){
while(isdigit(s[++i] = c = getch())){
; //integer part
}
}
if(c == '.'){
while(isdigit(s[++i] = c = getch())){
; //fraction part
}
}
s[i] = '\0';
if(c != EOF){
ungetch(c);
}
return NUMBER;
}
However the output isnt the same, the last input gets snipped off for some reason when using the alternative while loop. So entering 123 returns 12.
while(isdigit(c = getch())){
s[++i] = c;
}
The original always increments i
and assigns to s[++i]
. Your version skips those two steps if the isdigit()
check fails. To match the behavior of the original you'd need to perform one extra assignment and increment after the loop ends.
while(isdigit(c = getch())){
s[++i] = c;
}
s[++i] = c;