当前位置:网站首页>Chapter 8 Character Input Output and Input Validation
Chapter 8 Character Input Output and Input Validation
2022-08-03 03:36:00 【Think of a name is really difficult】
8.1 单字符I/O:getchar()和putchar()
**getchar()和putchar()**每次只处理一个字符.
/******************************************************************************** * @author: Mr.Y * @date: 2022/5/2 17:35 * @description: A character from the keyboard input,And send these characters on the screen. * 程序使用while循环,当读到#字符时停止. * 存在的问题:If there is a special character(如:#)来结束输入,Cannot be used in the text the character,如何解决. ********************************************************************************/ #include <stdio.h> int main(void) { char ch; while ((ch = getchar()) != '#') putchar(ch); return 0; } /*** * output * Hello, there. I would * Hello, there. I would * like a #3 bag of potatoes. * like a */
8.2 缓冲区
In the old system running the above procedure may show as follows:
HHeelllloo,, tthheerree.. II wwoouulldd[enter] lliikkee aa #
Like this back to show the character of user input immediately after repeated print the character belongs to无缓冲输入,That is waiting for the program can be used immediately input character.
大部分系统在用户按下Enter键之前不会重复打印刚输入的字符,The input form belong to缓冲输入.User input characters are collected and stored in a known as缓冲区(buffer)的临时存储区,按下Enter键后,程序才可使用用户输入的字符.
为什么需要缓冲区?
- Compared several characters as a piece of transmitted by sending characters to save time.
- 如果输入错误,Can be directly through the keyboard to correct mistakes.
缓冲分类
- 完全缓冲I/O
- When the buffer is filled to refresh the buffer(内容被发送至目的地),通常出现在文件输入中.缓冲区的大小取决于系统,常见的大小是512字节和4096字节.
- 行缓冲I/O
- In the event of a newline refresh buffer.键盘输入通常是行缓冲输入,所以在按下Enter键后才刷新缓冲区.
- 完全缓冲I/O
Use buffered input or unbuffered input?
- ANSI C和后续的CStandards are input is缓冲的.
- ANSIDecided to buffer the input as standard is the cause of:一些计算机不允许无缓冲输入.
8.3 结束键盘输入
8.3.1 文件,流和键盘输入
- 文件(file)是存储器中存储信息的区域.通常,文件都保存在某种永久存储器中(如,硬盘,U盘等)
- 编写的CProgram is stored in the file,用来编译CThe program program is also stored in the file.后者说明,Some programs need to access the specified file,When compile stored in namedecho.cFile the application in,编译器打开echo.cFile and read the content.When the compiler after processing,会关闭文件.其他程序,如文字处理器,不仅要打开,读取和关闭文件,Also the data written to the file.
- CThere are a lot of to open,读取,写入和关闭文件的库函数.From the lower surface,CYou can use the host operating system of the basic tools to deal directly with the file,These direct call function of the operating system is referred to as底层I/O(low-level I/O).Due to different computer systems,So for ordinary底层I/OIn the standard library functions to create,ANSI C也不打算这样做.However, from a higher level,C还可以通过标准I/O包(standard I/O package)来处理文件.
- 从概念上看,C程序处理的是流而不是直接处理文件.流(stream)是一个实际输入或输出映射的理想化数据流.这意味着不同属性和不同种类的输入,由属性更统一的流来表示.于是,打开文件的过程就是把流与文件相关联,而且读写都通过流来完成.
- stdin流表示键盘输入,stdout流表示屏幕输出.getchar(),putchar(),printf()和scanf()Functions are standardI/O包的成员,Deal with the two flow.
8.3.2 文件结尾
检测文件结尾的一种方法是,Put a special character at the end of the file tag files at the end.
如今,The operating system can use the embeddedCtrl+Z字符来标记文件结尾.This was once the operating system USES only sign,But now there are some other options,Such as the size of the log files.So the modern text files don't necessarily have the embeddedCtrl+Z,但是如果有,The operating system will regard it as a file ending tag.
Operating systems use another method is to store the information of the file size.如果文件有3000字节,The program read3000Bytes when it reaches the end of the file.
在C语言中,用getchar()读取文件检测到文件结尾时将返回一个特殊的值,即EOF.scanf()函数检测到文件结尾时也返回EOF.通常,EOF定义在stdio.h文件中:
#define EOF (-1)
为什么是**-1**?因为getchar()The return value of a function is usually situated between0—127,这些值对应标准字符集.但是,If the system can identify the extended character set,The function return value may be0—255.无论哪种情况,-1Do not correspond to any character,所以,This value can be used to tag files at the end.
Some systems may putEOF定义为**-1以外的值,But the definition of value must be and a return value generated by the different input character.如果包含stdio.h文件,并使用EOF符号,就不必担心EOF**值不同的问题.
If you are reading is the keyboard is not files will be how to?Most systems have a way through the keyboard simulation file ending condition.如下代码:
/******************************************************************************** * echo_eof.c * @author: Mr.Y * @date: 2022/5/3 18:54 * @description: 重复输入,直到文件结尾 ********************************************************************************/ #include <stdio.h> int main(void) { int ch; while ((ch = getchar()) != EOF) putchar(ch); return 0; }
The above application note
- 不用定义EOF,因为stdio.h中已经定义过了.
- 不用担心EOF的实际值,因为EOF在stdio.h中用**#define预处理指令定义,可直接使用,不必再编写代码假定EOF**为某值.
- 变量ch的类型从char变为int,因为char类型的变量只能表示0—255的无符号整数,但是EOF的值是**-1**.还好,getchar()函数实际返回值的类型是int,所以它可以读取EOF字符.If the implementation using the signedchar类型,也可以把ch声明为char类型,But it is better to use a more general form.
- 由于getchar()函数的返回类型是int,如果把getchar()的返回值赋给char类型的变量,一些编译器会警告可能丢失数据.
- ch是整数不会影响putchar(),This function will still print equivalent character.
- 使用该程序进行键盘输入,要设法输入EOF字符,不能只输入字符EOF,也不能只输入**-1**.正确的方法是,必须找出当前系统的要求.如,在大多数UNIX和Linux系统中,In a row beginning pressCtrl+D会传输文件结尾信号.许多微型计算机系统都把一行开始处的Ctrl+Z识别为文件结尾信号,Some systems put anywhereCtrl+ZInterpreted as file ending signal.
8.4 重定向和文件
- The input and output involves the function,数据和设备.输入设备(假设)是键盘,The input data stream consists of characters.If you want to input function and data type the same,Only change the program to find the location of the data.那么,What do you know where to find the input program?
- 在默认情况下,CProgram using the standardI/OPackage for the standard input as the input source.即前面介绍的stdin流,It is commonly used way to put the data into the computer.Modern computers are very flexible,Can let it elsewhere for input.尤其是,Can make a program from a file for input,而不是键盘.
- 程序可以通过两种方式使用文件.
- Explicitly using a specific function to open the file,关闭文件,读取文件,写入文件,诸如此类.
- Design programs that can interact with the keyboard and screen,通过不同的渠道重定向Input to the file and the output from the file.
- 重定向One of the main problems is that it is related to the operating system,与C无关.
8.4.1 UNIX,Linux和DOS重定向
- UNIX(Run the command line mode),Linux(ditto)和Window命令行提示(Imitate the oldDOS命令行环境)Can redirect input,输出.Redirect input to the program using the file instead of the keyboard,Redirect the output to the program output to the file instead of the screen.
1,重定向输入
The file content to use the program input console.
Assumptions have been compiled in the program on itecho_eof.c程序,并生成一个名为echo_eof(在windows系统中名为echo_eof.exe)的可执行文件.运行程序,Input the executable file name.
The program runs as described earlier,获取用户从键盘输入的输入,Suppose now have to deal with,xxx的文本文件.Simply use the following command instead of the above command.
可执行文件名 < 文本文件名
<符号是UNIX和DOS/Windows的重定向运算符.The operator to makewords文件与stdio流相关联,把文件中的内容导入echo_eof程序.
2,重定向输出
Content of the console output to file.
假设要用echo_eof.exeApplication is sent to the contents of keyboard input is calledmyworlds的文件中.Use the following command and start the keyboard.
可执行文件名 > 文本文件名
符号**>Is the second redirection operator.它创建一个名为xxx的文件,Then put the executable file output redirected to the file.重定向把stdout从显示设备赋给xxx文件.如果已经有一个名为xxx**的文件,通常会擦除该文件的内容,然后替换新的内容.
3,组合重定向
- If you need to make amyworlds文件的副本,并命名为savewords.只需输入以下命令即可:
Use the following commands can be,因为命令与重定向运算符的顺序无关.
echo_eof.exe > savewords < myworlds
在一条命令中,输入文件名和输出文件名不能相同.
In the system using two redirection operator(<和>)时,需要遵守以下原则.
- Redirection operators to connect an executable program and a data file,不能用于连接一个数据文件和另一个数据文件,也不能用于连接一个程序和另一个程序.
- 使用重定向运算符不能读取多个文件的输入,也不能把输出定向至多个文件.
- 通常,文件名和运算符之间的空格不是必须的,除非是偶尔在UNIX shell,Linux shell或WindowsCommand prompt has special meanings, which is used to model the character.
UNIX,Linux或Windows/DOS还有**>>运算符,该运算符可以把数据添加到现有文件的末尾,而|**Operator can connect the output of a file to another file input.
8.5 友好的用户界面
8.5.1 Use buffered input
Input buffer is more convenient to use,Because before the input sent to the program,The user can edit the input.But in the use of input character,也会带来麻烦,Input buffer requires the user to pressEnterKey to send input.This action also transfer the newline character,The program must properly deal with the trouble of line breaks.
/******************************************************************************** * @author: Mr.Y * @date: 2022/7/19 15:21 * @description: The user to select a number,Guess the user's choice of digital process is a few. * 用户只能输入'n'或'y' ********************************************************************************/ #include <stdio.h> int main(void) { int guess = 1; char response; printf("Pick an integer from 1 to 100. I will try to guess "); printf("it.\nRespond with a y if my guess is right and with"); printf("\nan n if it is wrong.\n"); printf("Uh...is your number %d?\n",guess); while ((response = getchar()) != 'y') /*获取响应*/ { if (response == 'n') printf("Well, then, is it %d\n",++guess); else printf("Sorry, I understand only y or n.\n"); while (getchar() != '\n') continue; /*Skip the rest of the input line*/ } return 0; } /** *output * D:\code\CLion\C_Primer_Plus\cmake-build-debug\guess.exe * Pick an integer from 1 to 100. I will try to guess it. * Respond with a y if my guess is right and with * an n if it is wrong. * Uh...is your number 1? * 1 * Sorry, I understand only y or n. * n * Well, then, is it 2 * q * Sorry, I understand only y or n. * y Process finished with exit code 0 **/
8.5.2 Hybrid numerical and character input
Assume that the program calls for**getchar()Processing character input,用scanf()Numerical input processing,These two functions can complete the task very well,But can not be used them.因为getchar()读取每个字符,包括空格,制表符和换行符;而scanf()**在读取数字时则会跳过空格,制表符和换行符.
/******************************************************************************** * @author: Mr.Y * @date: 2022/7/20 18:23 * @description: Program reads a single character and two Numbers,Then according to the input of the two Numbers specified rows and columns to print the character ********************************************************************************/ #include <stdio.h> void display(char cr,int lines,int width); int main(void) { int ch; /*待打印字符*/ int rows,cols; /*行数和列数*/ printf("Enter a character and two integers:\n"); while ((ch = getchar())!='\n') { if(scanf("%d %d",&rows,&cols) != 2) break; display(ch,rows,cols); while (getchar()!='\n') continue; printf("Enter another character and two integers;\n"); printf("Enter a newline to quit.\n"); } printf("Bye.\n"); return 0; } void display(char cr,int lines,int width) { int row,col; for (row = 1; row <= lines ; row++) { for(col = 1;col <= width;col++) putchar(cr); putchar('\n'); } } /* * output * Enter a character and two integers: * w 3 4 * wwww * wwww * wwww * Enter another character and two integers; * Enter a newline to quit. * t 3 6 * tttttt * tttttt * tttttt * Enter another character and two integers; * Enter a newline to quit. * Bye. * */
边栏推荐
猜你喜欢
随机推荐
成都高新南区 高新西区 东部新区 多边形范围点位 AOI 高德
金仓数据库 OCCI 迁移指南(5. 程序开发示例)
基于flowable的upp(统一流程平台)运行性能优化(2)
leetcode:139. 单词拆分
重定向printf到USB CDC、串口2
百度超级链:鼓励企业做自己的链
C语言实验十二 指针(二)
05-分布式计算框架
Useful Monitoring Scripts What you want part1 in Oracle
QCheckBox、margin、border、pandding、QHoxLayout、QSplitter、QSpacerItem
nVisual信息基础设施可视化管理
基于flowable的upp(统一流程平台)运行性能优化(3)
IDEA如何创建父子工程
IDEA如何创建同级工程
JWT入门学习
金仓数据库 Pro*C 迁移指南(3. KingbaseES Pr*oc 对 Oracle Pro*c 的兼容)
【 original 】 Auto. Js the get and post case
密码学的基础:X.690和对应的BER CER DER编码
Postman如何做接口自动化测试?
ldap创建公司组织、人员