scanf()将新行char留在缓冲区中 [英] scanf() leaves the new line char in the buffer

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

问题描述

我有以下程序:

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 new line 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)中的文字文本; 也不跳过空格。文字订单必须匹配要读取的下一个字符。

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.

所以您可能想要 order =%d 如果您想从上一行跳过换行符,但仍需要在固定字符串喜欢这个问题

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()将新行char留在缓冲区中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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