Specifying the maximum number of characters that can be read. - C String

C examples for String:char array

Description

Specifying the maximum number of characters that can be read.

Demo Code

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

#define SIZE 20//w w w  .j  av a 2  s .  c o m

char * getword(char *target, int max);

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

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

  return 0;
}

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

  while ((ch = getchar()) != EOF && i < max)  {
    if (isspace(ch)){
      if (inword)
        break; // word is over, exit while loop
      else{
        continue; // skip leading whitespace
      }
    }
    // if ch is not 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