Read string and stops after n characters or after the first blank, tab, or newline, whichever comes first - C String

C examples for String:char array

Description

Read string and stops after n characters or after the first blank, tab, or newline, whichever comes first

Demo Code

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

#define SIZE 20//w  w  w.  j av a2 s .  co  m

char * sgetnchar(char *array, int n);

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

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

  return 0;
}

// get characters from input and store them in character array,
// stopping after n characters or first whitespace
char * sgetnchar(char *array, int n){

  int i = 0;
  char ch;

  while ((ch = getchar()) != EOF && !isspace(ch) && i < n){
    *(array + i) = ch;
    i++;
  }

  return array;
}

Result


Related Tutorials