scanf() 将换行符留在缓冲区中 [英] scanf() leaves the newline character in the buffer

查看:41
本文介绍了scanf() 将换行符留在缓冲区中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序:

int main(int argc, char *argv[])
{
  int a, b;
  char c1, c2;
  printf("Enter something: ");
  scanf("%d",&a); // line 1
  printf("Enter other something: ");
  scanf("%d", &b); // line 2

  printf("Enter a char: ");
  scanf("%c",&c1); // line 3
  printf("Enter another char: ");
  scanf("%c", &c2); // line 4

  printf("Done"); // line 5

  system("PAUSE");

  return 0;
}

正如我在 C 书中看到的,作者说 scanf() 在缓冲区中留下了一个换行符,因此,程序不会在第 4 行停止让用户输入数据,而是将换行符存储在 c2 中并移至第 5 行.

As I read in the C book, the author says that scanf() left a newline character in the buffer, therefore, the program does not stop at line 4 for user to enter the data, rather it stores the new line character in c2 and moves to line 5.

是吗?

但是,这仅发生在 char 数据类型中吗?因为我没有看到第1、2、3行的int数据类型有这个问题,对吗?

However, does this only happen with char data types? Because I did not see this problem with int data types as in line 1, 2, 3. Is it right?

推荐答案

scanf() 函数在尝试解析字符以外的转换之前自动跳过前导空格.字符格式(主要是 %c;也扫描集 %[…] — 和 %n)是例外;他们不会跳过空格.

The scanf() function skips leading whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c; also scan sets %[…] — and %n) are the exception; they don't skip whitespace.

使用带有前导空格的 " %c" 来跳过可选的空格.不要在 scanf() 格式字符串中使用尾随空格.

Use " %c" with a leading blank to skip optional white space. Do not use a trailing blank in a scanf() format string.

请注意,这仍然不会消耗输入流中留下的任何尾随空格,甚至不会消耗到行尾,所以如果还使用 getchar()fgets() 在同一个输入流上.我们只是让 scanf 在 转换之前跳过空格,就像 %d 和其他非字符转换一样.

Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar() or fgets() on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d and other non-character conversions.

注意非空白指令"(使用 POSIX scanf 术语) 除了转换,例如 scanf("order = %d", &order); 中的文字文本也不会跳过空格.文字 order 必须与要读取的下一个字符匹配.

Note that non-whitespace "directives" (to use POSIX scanf terminology) other than conversions, like the literal text in scanf("order = %d", &order); doesn't skip whitespace either. The literal order has to match the next character to be read.

因此,如果您想从上一行跳过换行符,但仍需要对固定字符串 喜欢这个问题.

So you probably want " order = %d" there if you want to skip a newline from the previous line but still require a literal match on a fixed string, like this question.

这篇关于scanf() 将换行符留在缓冲区中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆