I am fairly new to C. I want to fill a 2d array where each row is filled using a string as input. My current solution looks as follows:
char word[2][100]
for (int i = 0; i < 2; i++) {
scanf(" %[^\n]", word[i]);
}
I generally understand the %[^\n] specifier but don't understand why space is needed before it in order to work.
When I try to do the same with %s things start to go weird.
char word[2][100]
for (int i = 0; i < 2; i++) {
scanf("%s", word[i]);
}
It allows for 3 Inputs instead of 2 and crashes my program.
"%s"
skips leading white-space, even without a leading " "
, like ' '
and the previous line's '\n'
due to Enter.
" %[^\n]"
also skips leading white-space due to the " "
, else it does not. Then it looks for non-'\n'
input.
Both are bad as they lack width control and neither properly reads a line.
Consider avoiding scanf()
and use fgets()
.
char word[2][100] = { 0 };
for (int i = 0; i < 2; i++) {
char buffer[100 + 1];
if (fgets(buffer, sizeof buffer, stdin) == NULL) break;
buffer[strcpsn(buffer, "\n")] = '\0'; // lop off potential trailing \n
strcpy(word[i], buffer);
}
There are additional concerns too, but something to get OP started.