关于在 C 中检测行尾的说明
Explanation about detecting end of line in C
我 reading/practicing 正在阅读这本关于 C 语言的书:"C Programming - A Modern Approach 2" 我偶然发现了这段代码,它的解释对我来说很奇怪:
Since scanf doesn't normally skip white spaces, it's easy to detect the end of an input line: check to see if the character just
read is the new-line character. For example, the following loop
will read and ignore all remaining characters in the current input
line:
do {
scanf("%c", &ch);
} while (ch != '\n');
When scanf is called the next time, it will read the first character on the next input line.
我了解代码的功能(它在检测到 enter 或 '\n'
时退出循环)但不了解课程(?)。
这样做的目的是什么,因为要将用户的输入存储到 &ch
中,您必须按 enter 键(退出循环)?
还有"the following loop will read and ignore all remaining characters in the current input line"到底是什么意思?
...这个...的目的是什么
要了解此代码片段的用途,请查看 this link discussing stdio buffering。
用最简单的逻辑术语来说,此技术会消耗放置在 stdin 中的内容,直到看到 newline
字符。 (来自用户按下 <enter>
键。)这显然是教训。
这有效地清除了内容的 stdin
缓冲区,也描述了 in this more robust example。
还有什么作用
"the following loop will read and ignore all remaining characters in
the current input line"
实际上是什么意思?
do {
scanf("%c", &ch);
} while (ch != '\n');
表示如果scanf
刚刚读取的新char
不等于换行符,定义为\n
,则继续覆盖c
与下阅读。一旦 ch
等于 \n
,循环就会退出。
我 reading/practicing 正在阅读这本关于 C 语言的书:"C Programming - A Modern Approach 2" 我偶然发现了这段代码,它的解释对我来说很奇怪:
Since scanf doesn't normally skip white spaces, it's easy to detect the end of an input line: check to see if the character just read is the new-line character. For example, the following loop will read and ignore all remaining characters in the current input line:
do {
scanf("%c", &ch);
} while (ch != '\n');
When scanf is called the next time, it will read the first character on the next input line.
我了解代码的功能(它在检测到 enter 或 '\n'
时退出循环)但不了解课程(?)。
这样做的目的是什么,因为要将用户的输入存储到 &ch
中,您必须按 enter 键(退出循环)?
还有"the following loop will read and ignore all remaining characters in the current input line"到底是什么意思?
...这个...的目的是什么
要了解此代码片段的用途,请查看 this link discussing stdio buffering。
用最简单的逻辑术语来说,此技术会消耗放置在 stdin 中的内容,直到看到 newline
字符。 (来自用户按下 <enter>
键。)这显然是教训。
这有效地清除了内容的 stdin
缓冲区,也描述了 in this more robust example。
还有什么作用
"the following loop will read and ignore all remaining characters in the current input line"
实际上是什么意思?
do {
scanf("%c", &ch);
} while (ch != '\n');
表示如果scanf
刚刚读取的新char
不等于换行符,定义为\n
,则继续覆盖c
与下阅读。一旦 ch
等于 \n
,循环就会退出。