Reads the first word from a line of input into an array and discards the rest of the line. - C String

C examples for String:char array

Introduction

A word is a sequence of characters with no blanks, tabs, or newlines in it.

Demo Code

#include <stdio.h>  
#include <ctype.h>  
#define LEN 80  //  ww  w . j a v a  2  s .  c  om

char * getword(char * str);  

int main(void)  {  
    char input[LEN];  
      
    while (getword(input) != NULL)  
        puts(input);  
    puts("Done.\n");  
      
    return 0;  
}  
  

char * getword(char * str)  
{  
    int ch;  
    char * orig = str;  

    while ((ch = getchar()) != EOF && isspace(ch))      // skip over initial whitespace  
        continue;  
    if (ch == EOF)  
        return NULL;  
    else  
        *str++ = ch;   // first character in word  
    
    // get rest of word  
    while ((ch = getchar ()) != EOF && !isspace(ch))  
        *str++ = ch;  
    *str = '\0';  
    if (ch == EOF)  
        return NULL;  
    else  
    {  
        while (ch != '\n')  
            ch = getchar();  
        return orig;  
    }  
}

Result


Related Tutorials