【问题标题】:scanf not reading mycharsscanf 不读取 mychars
【发布时间】:2016-09-01 20:58:56
【问题描述】:

我正在使用表格为指针进行可视化显示。 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;
}

【问题讨论】:

  • 变量“不起作用”是什么意思?
  • @user3121023 谢谢。为什么会起作用?
  • 顺便说一句:你如何检查 length 和来自 scanf(" %[^\n]s", mychars); 的输入长度是否合适?
  • @deamentiaemundi 我应该多写一个if吗?
  • %s 允许添加字段宽度,您可以使用它。

标签: c pointers memory scanf truncate


【解决方案1】:

不要使用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 \0
  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;
}

【讨论】:

  • 我不确定我是否理解您的高级代码并且它运行不正确。这是我得到的:$ runc.py newstat 删除 "newstat.exe" 删除 编译 编译!执行空间------------------------------------------------ - 长度? 10 ------------------------------------------------- - 按任意键继续 。 . .
  • @Clayton Wahlstrom 1) 单步执行代码。 2) 代码可能在 return -1; 之一上退出 3) 怀疑您正在使用不兼容的 C 编译器,该编译器与 "%zu" 存在问题 - 更改为 "%u" 并使用类型 unsigned 而不是 size_t
  • @ClaytonWahlstrom 好吧,tested(您只需在最后一个 f 上添加一个 f),它就会按预期“工作”。
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多