Using fgets() to read string from console - C File

C examples for File:File Read

Description

Using fgets() to read string from console

Demo Code

#include <stdio.h>
#define STLEN 10//from   ww w . jav a2 s  .  c  o m
int main(void)
{
    char words[STLEN];
    int i;
    
    puts("Enter strings (empty line to quit):");
    while (fgets(words, STLEN, stdin) != NULL && words[0] != '\n')
    {
        i = 0;
        while (words[i] != '\n' && words[i] != '\0')
            i++;
        if (words[i] == '\n')
            words[i] = '\0';
        else // must have words[i] == '\0'
            while (getchar() != '\n')
                continue;
        puts(words);        
    }
    puts("done");
    return 0;
}

Result


Related Tutorials