scanf()的叶子在缓冲区中的新行字符? [英] scanf() leaves the new line char in buffer?

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

问题描述

我学习C和有一些问题。我知道我的问题可能是一个共同的问题,但我无法找到答案。
我有以下程序:

I am learning C and have some questions. I know my questions may be a common question but I could not find the answer. I have the following program:

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("%d",&c1); // line 3
  printf("Enter other char: ");
  scanf("%d", &c2); // line 4

  printf("Done"); // line 5

  system("PAUSE");  

  return 0;
}

正如我在C书上看到,作者说,scanf()的留在缓冲区的新行字符,因此,程序不会在用户线4停止输入数据,而是存储新线字符C2和移动到第5行,对吗?
不过,我想知道这只是用char数据类型发生呢?因为我没有看到这个问题,int数据类型,在1号线,2,3,这是正确的?

As I read in the C book, the author say 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. Is that right? However, I was wondering this only happen with char data types? Because I did not see this problem with int data types as in line 1, 2, 3. It is right?

感谢。

推荐答案

scanf函数函数试图解析字符以外的东西之前,会自动删除空白。字符格式(主要是%C )是例外;他们不删除空格。

The scanf function removes whitespace automatically before trying to parse things other than characters. The character formats (primarily %c) are the exception; they don't remove whitespace.

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

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