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

C examples for String:char array

Description

Read the first word from input into an array and discards the rest of the line

Demo Code

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

#define SIZE 20/*from   ww w .ja  va 2 s .  c om*/

char * getword(char *target);

int main(void){
  char hello[SIZE] = "Hello, ";

  printf("What's your name?");
  getword(hello + 7);
  puts(hello);

  return 0;
}

char * getword(char *target){
  char ch;
  int i = 0;
  bool inword = false;

  while ((ch = getchar()) != EOF)  {
    if (isspace(ch)){
      if (inword)
        break; // word is over, exit while loop
      else{
        continue; // skip leading whitespace
      }
    }
    if (!inword)
      inword = true;

    *(target + i) = ch;
    i++;
  }
  // discard rest of the line if any
  if (ch != '\n')
    while ((ch = getchar()) != '\n')
      continue;

  return target;
}

Result


Related Tutorials