我是编程新手,正在学习 C 编程基础知识。我正在学习 scanf()
是如何工作的,但我想现在我很困惑,真的不知道该问什么以及如何问。但我会尽力把我的问题说清楚。
问题
- 我真的无法理解空白的整个概念。我的意思是什么时候它们被
scanf
跳过,什么时候没有,最大的问题是:它们是如何被跳过的? 连同空格的概念,我也无法理解
scanf
函数的工作原理吗?我在许多书籍和网站以及本网站上都读过它,但它让我更加困惑,因为每个人都有自己讲述任何概念的方式,而且每个人的方式都不一样。看看这个短程序:
#include<stdio.h> int main() { int num; char ch; printf("enter the value of num and ch:\n"); scanf("%d",&num); scanf("%c",&ch); printf("num = %d and ch = %c",num,ch); return 0; }
我知道在这个程序中,用户将被允许只输入
num
的值,因为换行符留在输入缓冲区中,下次scanf
将输入该换行符,但如果我们在第二个 scanf 函数中的%c
之前添加额外的空格,则可以解决。但是当我将
char ch
变量替换为int ch
时,scanf
会跳过新行。 为什么?为什么 scanf 不会像空白一样跳过非空白字符 例如 - a, b, c, d, @) # 等?
scanf
中的space
和newline
字符有什么区别?我的意思是会有一些异常(exception),对吗?
最佳答案
第一个问题
I mean when they are skip by the scanf and when they are not
除非格式说明符是 %c
、%n
或 %[
,否则将跳过空白字符。 C11标准的相关引用:
7.21.6.2 The fscanf function
[...]
- Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
, orn
specifier. 284)
How they are skipped?
只需阅读并丢弃它们。
第二个问题
I'm not able to understand the working of scanf function also?
scanf
是一个 variadic function这意味着它可以接受任意数量的参数,最少有一个。 scanf
解析第一个参数,它是一个字符串文字,因此接受输入。
第三个问题
But when I replace the char ch variable with int ch, scanf skips the new line. Why?
第一个答案的第一部分对此进行了解释。 %d
将跳过空白字符。
第四题
Why scanf do not skip non-white space character just like whitespace?
对于某些转换说明符,如 %c
,非空白字符是有效输入。他们为什么要跳过它们是没有意义的。对于其他类似 %d
,字符(不是数字)是无效输入。 scanf
在发现无效输入时停止扫描并返回。它是这样设计的。
第五题
What is the difference between space and newline character in scanf?
在scanf
中将它们中的任何一个放在格式字符串中都没有区别。它们都被认为是 whitespace characters ,虽然他们是不同的角色。当它们用于 scanf
的格式字符串时,它们会跳过任意数量的空白字符(包括无),直到第一个非空白字符。 C11标准的相关引用:
7.21.6.2 The fscanf function
[...]
- A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.
关于c - 删除和添加空白字符到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452555/