【问题标题】:CLion won't print in console after scanfscanf 后 CLion 不会在控制台中打印
【发布时间】:2017-11-17 23:52:21
【问题描述】:

CLion 中的控制台在扫描输入后不会打印行,但在 iTerm 中编译后一切正常。 代码:

#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName;
    printf("Hello, what is your name?\n");
    scanf("%s", personName);
    printf("Hello, %s\n", personName);
    return 0;
}

我刚刚在 CLion 控制台中得到了这个:

Hello, what is your name?
Mike

Process finished with exit code 11

【问题讨论】:

  • 未定义行为personName 不是字符串。
  • 一半的标签完全不相关。选择一种 C 或 C++,但要知道,如果它打算成为 C++,那么你是从大约 25 年过时的资源中接受教育的。
  • 编译器warn about this.
  • 值得一读,这样下次您看到 Process finished with exit code 11 时,您就会知道它的含义:stackoverflow.com/questions/31103254/…
  • 在有人输入一个 51 个字符长的名字之前有效。

标签: c


【解决方案1】:

您需要为personName 使用数组。代码将是,

#include <stdio.h>
#include <stdlib.h>
int main() {
    char personName[32];
    printf("Hello, what is your name?\n");
    if(scanf("%s", personName))
        printf("Hello, %s\n", personName);
    return 0;
}

【讨论】:

  • 使用短至 10 的长度,虽然比问题好一个数量级,但并不“安全”;它太容易溢出了。最好使用char personName[32];if (scanf("%31s", personName) == 1) printf("Hello, %s\n", personName);。长度上的不同是不幸的,但被历史所尊崇并被载入标准。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2020-06-29
  • 1970-01-01
  • 2013-01-02
相关资源
最近更新 更多