scanf 不读取 mychars

scanf not reading mychars

我正在使用 table 为指针制作视觉显示。 length 的第一个输入有效,但未读取 mychars。我知道 scanf 之后有一个新行,但我不知道它的行为方式。 mycharsscanf 在我的特定情况下是如何解析的?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    int length;
    printf("Length? ");
    scanf("%d", &length);

    char *mychars = (char *)calloc(length, sizeof(char));

    printf("mychars? ");
    scanf("%[^\n]s", mychars);
    printf("mychars is \"%s\"\n", mychars);
    printf("pointer at %p\n", mychars);
    if (strlen(mychars) == length) {
        printf("Address    Location        Value\n");
        int i;
        for (i = 0; i < length; i++) {
            printf("%-10p *(mychars+%02d) %3c\n", (mychars+i), i, *(mychars+i));
        }
    } else {
        print("Not right length");
    }
    free(mychars);
    return 0;
}

不要使用scanf()。这是邪恶的。它不能很好地处理问题,并且容易被学习者误用。使用 fgets().

// untested code
int main(void) {
  size_t length;  // Use size_t for array sizes
  printf("Length? ");
  fflush(stdout); // Insure prompt is displayed before input.

  char buf[50];
  if (fgets(buf, sizeof buf, stdin) == NULL) return -1;
  if (sscanf(buf, "%zu", &length) != 1) return -1;

  char *mychars = malloc(length + 2);  // +1 for \n, +1 for [=10=]
  if (mychars == NULL) return -1;

  printf("mychars? ");
  fflush(stdout);
  if (fgets(mychars, length + 2, stdin) == NULL) return -1;
  // lop off potential \n
  mychars[strcspn(mychars, "\n")] = 0;

  printf("mychars is \"%s\"\n", mychars);
  printf("pointer at %p\n", (void*) mychars);  // Use `void *` with %p

  if (strlen(mychars) == length) {
    printf("Address    Location        Value\n");
    size_t i;
    for (i = 0; i < length; i++) {
      printf("%-10p *(mychars+%02zu) %3c\n", (void*) (mychars + i), i, *(mychars + i));
    }
  } else {
    printf("Not right length\n");  // add \n
  }
  free(mychars);
  return 0;
}