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?