strchr
could be used to look for a newline. If found, set the newline to zero to terminate the string. Call fgets
to fill the remainder of the array. The loops continue until both arrays are filled.
The array with size [4] can store three characters and a terminating zero.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void) {
char a[4];
char b[4];
char *newline = NULL;
size_t len = 0;
fgets(a, sizeof(a), stdin);
while ( ( newline = strchr ( a, '\n'))) {//find a newline
*newline = 0;//set terminating zero
len = strlen ( a);
if ( len < sizeof a - 1) {//space available in array
fgets ( newline, sizeof a - len, stdin);//more input into array
}
else {
break;
}
}
fgets(b, sizeof(b), stdin);
while ( ( newline = strchr ( b, '\n'))) {//find a newline
*newline = 0;//set terminating zero
len = strlen ( b);
if ( len < sizeof b - 1) {//space available in array
fgets ( newline, sizeof b - len, stdin);//more input into array
}
else {
break;
}
}
fprintf(stderr, "%s%s\n", a, b);
return 0;
}
getchar
could be used to clear the input stream if the first array does not contain a newline.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void) {
char a[4];
char b[4];
fgets(a, sizeof(a), stdin);
if ( ! strchr ( a, '\n')) {//no newline
while ( '\n' != getchar ( )) {//clear the input stream
if ( EOF == getchar ( )) {
fprintf ( stderr, "problem EOF\n");
return 1;
}
}
}
fgets(b, sizeof(b), stdin);
fprintf(stderr, "%s%s\n", a, b);
return 0;
}