简体   繁体   English

输入来自Kernighan和Ritchie的例子

[英]Input for examples from Kernighan and Ritchie

In section 1.5.2 of the 2nd ed. 在第2版的第1.5.2节中。 K&R introduce getchar() and putchar() and give an example of character counting, then line counting, and others throughout the chapter. K&R介绍了getchar()和putchar(),并给出了一个字符计数,然后是行计数以及本章其他内容的示例。

Here is the character counting program 这是字符计数程序

#include <stdio.h>
main() {

long nc;

nc = 0;
while (getchar() != EOF)
    ++nc;
printf("%ld\n",nc);
}

where should the input come from? 输入应该来自哪里? typing into the terminal command window and hitting enter worked for the file copying program but not for this. 键入终端命令窗口并按Enter键为文件复制程序工作但不是为此。 I am using XCode for Mac. 我正在使用XCode for Mac。

It seems like the easiest way would be to read a text file with pathway "pathway/folder/read.txt" but I am having trouble with that as well. 看起来最简单的方法是读取带有“pathway / folder / read.txt”路径的文本文件,但我也遇到了麻烦。

From the interactive command line, press ctrl-D after a newline, or ctrl-D twice not after newline, to terminate the input. 从交互式命令行,按下Ctrl-d换行符后,或CTRL-D两次换行之后,以终止输入。 Then the program will see EOF and show you the results. 然后程序将看到EOF并显示结果。

To pass a file by path, and avoid the interactive part, use the < redirection operator of the shell, ./count_characters < path/to/file.txt . 要按路径传递文件,并避开交互式部分,请使用shell的< redirection operator,。 ./count_characters < path/to/file.txt

Standard C input functions only start processing what you type in when you press the Enter key IOW.Every key you press adds a character to the system buffer (shell).Then when the line is complete (ie, you press Enter), these characters are moved to C standard buffer. 标准C输入功能仅在您按下Enter键时开始处理您键入的内容IOW。您按下的每个键都会向系统缓冲区(shell)添加一个字符。然后当该行完成时(即按Enter键),这些字符被移动到C标准缓冲区。 getchar() reads the first character in the buffer, which also removes it from the buffer.Each successive call to getchar() reads and removes the next char, and so on. getchar()读取缓冲区中的第一个字符,该字符也将其从缓冲区中删除。每次连续调用getchar()读取并删除下一个字符,依此类推。 If you don't read every character that you had typed into the keyboard buffer, but instead enter another line of text, then the next call to getchar() after that will continue reading the characters left over from the previous line; 如果你没有读到键入缓冲区的每个字符,而是输入另一行文本,那么下一次调用getchar()将继续读取前一行留下的字符; you will usually witness this as the program blowing past your second input. 你通常会看到这个程序超过你的第二个输入。 BTW, the newline from the Enter key is also a character and is also stored in the keyboard buffer, so if you have new input to read in you first need to clear out the keyboard buffer. 顺便说一句,Enter键的换行符也是一个字符,也存储在键盘缓冲区中,所以如果要读入新输入,首先需要清除键盘缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM