Fetches the next n characters from input (including blanks, tabs, and newlines), storing the results in an array whose address is passed as an argument. - C String

C examples for String:char array

Description

Fetches the next n characters from input (including blanks, tabs, and newlines), storing the results in an array whose address is passed as an argument.

Demo Code

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

#define SIZE 20//from   ww  w  . j  a v a2 s. c o m

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

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

  printf("What's your name? (enter %d characters)\n", space);
  sgetnchar(hello + 7, space);
  puts(hello);

  return 0;
}
// gets n characters from input and stores them in character array
char * sgetnchar(char *array, int n){
  char ch;

  for (int i = 0; i < n; i++){
    if ((ch = getchar()) == EOF)
      break;
    *(array + i) = ch;
  }
  return array;
}

Result


Related Tutorials