【问题标题】:scanf is reading new line characterscanf 正在读取换行符
【发布时间】:2017-06-25 06:26:11
【问题描述】:

scanf() 总是丢弃空格和换行符。但是当我给出一个字符并按下回车时,新行字符被读取并存储。因此,我无法读取所需的字符数。我的代码有什么问题,还是其他什么问题?

gets 也有同样的问题。许多帖子建议使用fgets(),而不是使用以上两者,但我需要知道为什么会发生这种情况。

【问题讨论】:

  • 请复制并粘贴代码而不是快照。
  • nm 声明在哪里?还有char **str = malloc (sizeof *str * n);str[row] = malloc (sizeof *str[row] * m);(这些是指针,不是您当前问题的原因)。请发帖A Minimal, Complete, and Verifiable examplefflush (stdin) 是未定义的行为。
  • "scanf() 总是丢弃空格和换行符"...除非您使用不丢弃空格字符的%c%[] 格式。您正在使用%c
  • 您正在使用的%c 格式不会丢弃空格(包括换行符,因为它们是空格字符)。 fflush(stdin) 也有未定义的行为。如果要清除待处理的输入,请找到另一种方法。最后,尝试使用一些 C++ 流而不是 C I/O - 它们有几个优点,包括减少缓冲区溢出的机会(这就是 C 程序员推荐使用 fgets() 的原因)。
  • 你的代码看起来像 C 代码,而不是像 std::iostream 和 std::string 这样的东西,它会让你的生活更轻松。

标签: c++ newline scanf


【解决方案1】:

对于%c,手册页显示(参见http://man7.org/linux/man-pages/man3/scanf.3.html):

c      Matches a sequence of characters whose length is specified by
       the maximum field width (default 1); the next pointer must be
       a pointer to char, and there must be enough room for all the
       characters (no terminating null byte is added).  The usual
       skip of leading white space is suppressed.  To skip white
       space first, use an explicit space in the format.

注意部分:通常跳过前导空白被抑制。

还要注意部分:跳过白色 空格优先,在格式中使用显式空格。

因此,如果您想跳过空格,请尝试在 %c 之前添加一个空格:

char c;
scanf(" %c", &c);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2013-07-04
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多