Search code examples
cwhile-loopgetchar

How to input one word and read each letter and print via loop C


I would like to input 5 words one word at a time and then with that word print out each letter of the word. However, I enter a while loop and it looks like the while loop never terminates after I enter the first word.

const int amountOfInputs = 5;    
 
for (int i = 1; i <= amountOfInputs; ++i)
{
    printf("Word Number # %d :\n", i );
    
    char reader;
    while(reader = getchar(), reader >= 0 ) 
    {
        printf("letters of word %d are: %c \n", i, reader);
    }
}

Output:

enter image description here


Solution

  • Change the while loop the following way

    #include <ctype.h>
    
    //...
    
    int reader;
    while( ( reader = getchar() ) != EOF && reader != '\n' && !isblank( ( unsigned char )reader ) ) 
    //...
    

    That is separators of words are the space character ' ', the tab character '\t' or the new line character '\n'. If you want to include spaces in words then the condition of the loop will look simpler

    int reader;
    while( ( reader = getchar() ) != EOF && reader != '\n' )