I was writing a code to print all the strings stored in 2d array after the user has finished typing the strings along with mentioning the maxlength of each string and total number strings (it will finally print the string along with the line number). The problem is that the code actually stores all the strings in the 2d array with one whole line of spacing i.e, one full empty row. The code, expected output and the output it is giving is below.
Code:
#include <stdio.h>
int main() {
char s[20][30];
int i, number_of_strings, length_of_string, j = 0;
scanf("%d %d", &number_of_strings, &length_of_string);
for (i = 0; i<number_of_strings; i++) {
while ((s[i][j++] = getchar()) != '\n' && j<length_of_string)
s[i][j] = '\0';
j = 0;
}
for (i = 0; i<number_of_strings; i++) {
printf("i= %d %s\n", i, s[i]);
}
return 0;
}
Sample Input:
2 3
raj
jar
Expected Output:
i= 0 raj
i= 1 jar
Output giving:
i= 0
i= 1 raj
i= 2
i= 3 jar
Please rectify where am I doing mistake.
intread ? what do you suppose that does to your first loop iteration ?\nbefore it consumes in your next iteration.scanf("%d %d", &number_of_strings, &length_of_string);leaves the\nof2 3\nin the buffer and the firstgetchar()reads it.while ((s[i][j++] = getchar()) != '\n' && j<length_of_string) s[i][j] = '\0';==> size test first as(j + 1) <length_of_string\nis in your buffer. This is the problem.