You have not shown the input value of n
and m
in the question. But from the input and output string shown, it seems that char
array a[i]
does not have the enough space for terminating null-character \0
. When you give format specifier %s
, scanf()
automatically adds a terminating null character at the end of the stored sequence. I tried your code with input 2
for both n
and m
and I am getting the output as you are getting:
$ ./a.out
2 2
ab
cd
abcd
cd
Give the value 4
to m
and the output is:
2 4
ab
cd
ab
cd
When using scanf()
for string input, it is good to add check for max character modifier that is 1
less than the length of the input buffer. So, if the size of input buffer is 4
then you can do
scanf("%3s",a[i]);
With this, the scanf()
will read not more than 3
characters in a[i]
and will add \0
at the fourth location of a[i]
. Beware with this, it does not discard the remaining input from input stream and they will be consumed by consecutive scanf()
call.
If you want to drop the extra input which wasn't consumed by scanf, one way of doing it is to read and discard the extra input using a loop, like this:
int c;
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
You can add it after scanf()
reads data from input stream, like this:
for(i=0; i<n; i++) {
scanf("%3s", a[i]); // assuming the size of a[i] is 4
int c;
while((c = getchar()) != '\n' && c != EOF) // <=== This loop read the extra input characters and discard them
/* discard the character */;
}
This will work fine for the input that does not contain any whitespace characters. If your input contain any whitespace character, it may not behave as expected. Hence, I would suggest you to read about fgets()
which gives you better control for string input.
Check this: fgets
and this: How to read from stdin with fgets()?