Matt Hall
Matt Hall

Reputation: 330

using getchar() in C to send input to a char array

edit I change my for loops into a function called input, and initialized the value of c in said function. Also changed the branching condition inside the loop, so that it inserts '\0' to the fifth element if necessary. My original problem of string1 spilling into string2 still persists. I've gotten rid of fflush( stdin ) because I'm unsure if it is supported by Mac OSX El Capitan.

I have a program that is suppose to concatenate two strings, but I want to make sure that the user doesn't overfill the size of the array

Right now, if the first string is too long, it will write characters into the next string, which is undesirable - my intention is that any extra characters beyond the space of the array will simply be ignored.

void input( char *s1, int size ){
  for( int i = 0, c = 0; ( i < size ) && ( c != '\n' ); i++ ){
      c = getchar();

      if( i == size - 1 || c == '\n' )
          s1[i] = '\0';
      else
          s1[i] = c;
  }
}

int main(){
  const int SIZE = 5;
  char string1[ SIZE ]; // create a char array
  char string2[ SIZE ]; // and another one

  printf( "Enter two strings: " );

  input( string1, SIZE );
  printf("String1: %s\n", string1);
  input( string2, SIZE );
  printf("String2: %s\n", string2);
}

Example output...

Enter two strings: foobarr
String1: foob
String2: rr

How can I change this so that 'arr' is entirely ignored, and

getchar() 

in the second function call waits for new input?

Upvotes: 0

Views: 3024

Answers (1)

Matt Hall
Matt Hall

Reputation: 330

Okay this seems to work, I got clear_buffer() function from How to clear input buffer in C?.

void input( char *s1, int size ){

  for( int i = 0, c = 0; ( i < size ) && ( c != '\n' ); i++ ){
      c = getchar();

      // if we're out of space or the user is done with this string 
      if( i == size - 1 || c == '\n' ){

          // add null char to the array
          s1[i] = '\0';

          // if we added null char because we ran out of space
          if( i == size - 1 )
              clear_buffer();
      }
      //Otherwise add a char to the array
      else
          s1[i] = c;
  }
}

void clear_buffer(){
  char c = '\0';
  while (( c = getchar()) != '\n' && c != EOF) { }
}



int main(){
  const int SIZE = 5;

  printf( "Enter two strings: " );

  char string1[ SIZE ] = { '\0' }; // create a char array
  input( string1, SIZE );
  printf("String1: %s\n", string1);

  char string2[ SIZE ] = { '\0' }; // create another char array
  input( string2, SIZE );
  printf("String2: %s\n", string2);

  return 0;
}

Upvotes: 1

Related Questions