Search code examples
c

A program that prints its input one word per line


I want to print one word per line but the output is not printing the last character of each word. Can anyone help in finding the error?

#include <stdio.h>  
#define IN 1  /* Inside a text */  
#define OUT 0  /* Outside a text */ 
main()  
{  
    int c,nw,state;  
    state=OUT;  
    while((c=getchar())!=EOF) 
    {  
       if(c==' '||c=='\n'||c=='\t')  
       {  
            state=OUT;  
            printf("\n");                      
       }  

       else if(state==OUT)  
       {  
            putchar(c);   /* To print the first character */
            state=IN;  
            ++nw;  
            c=getchar();  
            putchar(c);  /* To print the other characters of the word*/
       }    
    }  
}  

Using the above code the last character of each word is not printed.


Solution

  • sample to fix

    #include <stdio.h>  
    
    #define IN  1 /* Inside a text */  
    #define OUT 0 /* Outside a text */ 
    
    int main(void){
        int c, nw=0, state=OUT;
    
        while((c=getchar())!=EOF){
            if(c==' ' || c=='\n' || c=='\t'){//if(isspace(c)){
                if(state == IN){
                    state = OUT;
                    putchar('\n');
                }
            } else {
                if(state == OUT){
                    state = IN;
                    ++nw;
                }
                putchar(c);
            }
        }
        //printf("\n%d\n", nw);
        return 0;
    }