c - K&R Exercise 1-9: output the input, replacing multiple blanks by a single blank -


i've been working through books on c trying c legs (sea-legs! it?!). i've finished exercise 1-9 k&r book, reference "write program copy input output, replacing each string of 1 or more blanks single blank." have question what's going on code, though--

#include <stdio.h>  //copy input output. replace each string of multiple spaces 1 single space  int main(int argc, char *argv[]){      int ch, lch;      // variables hold current , last characters, respectively       /* loop should 'put' current char, store current char in lc,      * loop back, 'get' new char , check if current , previous chars both spaces.      * if both spaces, nothing. otherwise, 'put' current char      */      for(ch = getchar(); (ch = getchar()) != eof; lch = ch){             if(ch == ' ' && lch == ' ')                     ;             else putchar(ch);     }      return 0; } 

this works, except first character input. instance, if first line input

"this          test" 

my code outputs

"his test".  

after dropping first character input, program works consistently meet exercise's demands.

can give me idea of mistake made in loop that's causing issue? other advice welcome well.

in for-loop statement, you're having bug.

for(ch = getchar(); (ch = getchar()) != eof; lch = ch){...} 

here, you're storing first character in ch, , again testing if (ch!=eof) again reading character input.

remove ch=getchar() initialisation statement; let in second part.

for(;(ch = getchar()) != eof; lch = ch){...} 

also, have initialise lch before making run lch not have value stored in before making comparison in first iteration of loop. so, let lch=0 initialised first.

for(lch = 0; (ch = getchar()) != eof; lch = ch){...} 

consider enabling warnings in compiler, detect , warn issue, fix it.

the above solve problem.

(thanks blue moon , hyde helping me modify answer.)


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -