This needs a correct answer. If you insist on using scanf()
, there's only one format string that is safe and will do what you want:
int main() {
char a[100] = "";
char b[100] = "";
scanf("%99[^\n]%*c", a);
scanf("%99[^\n]%*c", b);
printf("%s\n%s", a, b);
}
In your original string, you had [^\n]s
which is wrong, because [^\n]
is a conversion specifier itself, matching anything except a newline. So there shouldn't be an s
following it.
The next change is the 99
prepended. This ensures a maximum of 99
characters is converted -- plus one byte for the terminating 0
, you have exactly the 100 characters available in your array. Without that, if the user enters more than 99 characters, your buffer would overflow.
The last change is to append %*c
: %c
will match any character, in this case the newline that is left after matching %[^\n]
. But you're not interested in it, you just want to consume it. This is what the *
is for, it discards the result of the matching.
If you can, just use fgets()
like this, it is much simpler to use for this case:
int main() {
char a[100] = "";
char b[100] = "";
fgets(a, 100, stdin);
fgets(b, 100, stdin);
// if needed, strip newlines, e.g. like this:
size_t n = strlen(a);
if (n && a[n-1] == '\n') a[--n] = 0;
n = strlen(b);
if (n && b[n-1] == '\n') b[--n] = 0;
printf("%s\n%s", a, b);
}