当格式字符串以换行符结尾时,scanf 的行为是什么? [英] What's the behavior of scanf when the format string ends with a newline?

查看:43
本文介绍了当格式字符串以换行符结尾时,scanf 的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码:(假设x已经定义)

For the following code: (assuming x has been defined)

scanf("%d\n", &x);
printf("foo");

如果我按 1 和 ENTER,我希望程序打印 foo,但事实并非如此.我必须按 1、ENTER、2、ENTER 才能看到它打印 foo.

I expect the program to print foo if I press 1 and ENTER, but this is not the case. I have to press 1, ENTER, 2, ENTER to see it print foo.

现在的问题是为什么我需要输入一些东西加上另一个 ENTER 才能让 scanf 返回?不可能是 scanf 只需要比格式字符串多一个 ENTER ,因为按 1, ENTER, ENTER 也不起作用.事实上,无论我输入多少 ENTER,scanf 都会一直等待,直到我输入其他内容.

Now the question is why do I need to input something plus another ENTER to make scanf return? It could't be that scanf just need one more ENTER than in the format string because pressing 1, ENTER, ENTER won't work either. In fact, scanf will keep waiting no matter how many ENTERs I entered until I type in something else.

我已经在 Visual Studio 2010 和 MinGW 中尝试过这个示例,它们产生了相同的结果.那么如何解释呢?这是特定于 Windows 的吗?还是依赖编译器?或者只是这种 scanf 的用法会产生未定义的行为?

I have tried this example in Visual Studio 2010 and MinGW, and they produced the same result. So how can this be explained? Is this Windows-specific? or compiler dependent? or just this kind of usage of scanf yields undefined behavior?

推荐答案

scanf 格式字符串中的'\n'(以及空格、制表符、'\r''\f''\v') 使 scanf 忽略空格.

The '\n' in the scanf format string (as well as space, tab, '\r', '\f', and '\v') makes scanf ignore whitespace.

ENTER 是空格,所以 scanf 会尽可能多地忽略它,并且只有在看到不是空格的东西(2)时才会停止.

ENTER is whitespace, so scanf ignores as much of it as it can and only stops when it sees something not whitespace (the 2).

这篇关于当格式字符串以换行符结尾时,scanf 的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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