#include <stdio.h>
#include "readstring.h"
/*
  The function readstring reads n characters from 
  standard input and places them in the array s, 
  followed by a null terminator '\0'.
  
  s must have enough space to store n characters plus the null terminator
  
  More specifically readstring does the following:
  -Skips any leading whitespace
  -Reads up to n non-whitespace characters, storing them in s
  -If there were more than n consecutive non-whitespace characters 
   on the input stream, readstring discards the remaining ones until
   it finds whitespace or EOF   
  -readstring appends the null terminator \0 to the characters 
   that were read into s

  Returns 1 if it successfully read a string, 0 otherwise.
*/
  
int readstring(char *s, int n){
  int i = 0;
  scanf(" ");//Skip whitespace
  //While scanf reads one character, and we have not read too many,
  //and the character read was not white space, increase i:
  while(scanf("%c",&s[i]) == 1 && i < n && s[i] != ' ' && s[i] != '\n') {
    i++;
  }
  
  if(!feof(stdin)) { 
    //s[i] now holds the last character read (i.e. first character that should not be stored in s)
    //If s[i] is not white space, 
    //continue reading until we find white space or EOF
    while(s[i] != ' ' && s[i] != '\n' && 1 == scanf("%c", &s[i])) {};
  }
  
  //Replace s[i] with '\0' to null-terminate the string
  s[i] = '\0';
  //Return 1 if we managed to read a string, 0 otherwise.
  return i > 0;
}