简体   繁体   中英

How to fill a 2d array using "%s\n" instead of " %[^\n]"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM