I/O functions/buffers and byte streams, placeholders, getchar(), putchar()

I/O functions

The C language provides some functions for communicating with external devices, which are called input and output functions, or I/O functions for short. Input (import) refers to obtaining external data, and output (export) refers to transferring data to the outside.

Buffers and byte streams

Strictly speaking, the input and output functions do not directly communicate with external devices, but communicate indirectly through buffers. This section describes what caching is.

Ordinary files are generally stored on the disk. Compared with the CPU, reading or writing data to the disk is a very slow operation. Therefore, it is not feasible for the program to directly read and write to the disk. It may take half a day to execute a line of commands. The solution in C language is to set a cache area for this file in memory as long as you open a file.

When the program writes data to the file, the program first puts the data into the cache, and when the cache is full, the data inside will be written to the disk file at one time. At this time, the cache area is empty, and the program puts new data into the cache and repeats the whole process.

When a program reads data from a file, the file first puts part of the data in the cache, and then the program gets the data from the cache. When the cache is empty, the disk file puts new data into the cache and repeats the whole process.

The reading and writing speed of the memory is much faster than that of the disk, and the design of the cache reduces the number of reads and writes to the disk, greatly improving the execution efficiency of the program. Also, moving large chunks of data at once is much faster than moving small chunks of data multiple times.

This read-write mode is a bit like a stream for programs. It is not a one-time read or write of all data, but a continuous process. Operate a part of the data first, wait until the cache has processed this part of the data, and then operate the next part of the data. This process is called byte stream operation.

Since the cache is empty after reading, the byte stream can only be read once, and it cannot be read the second time. This is very different from reading a file.

The input and output functions of the C language, which involve reading and writing files, are all byte stream operations. The input function obtains data from the file and operates on the input stream; the output function writes data to the file and operates on the output stream.

printf()

printf()It is the most commonly used output function and is used for screen output. The prototype is defined in the header file stdio.h. For details, see the chapter "Basic Grammar".

scanf()

basic usage

scanf()函数用于读取用户的键盘输入。程序运行到这个语句时,会停下来,等待用户从键盘输入。用户输入数据、按下回车键后,scanf()就会处理用户的输入,将其存入变量。它的原型定义在头文件stdio.h

scanf()的语法跟printf()类似。

scanf("%d", &i);

它的第一个参数是一个格式字符串,里面会放置占位符(与printf()的占位符基本一致),告诉编译器如何解读用户的输入,需要提取的数据是什么类型。这是因为 C 语言的数据都是有类型的,scanf()必须提前知道用户输入的数据类型,才能处理数据。它的其余参数就是存放用户输入的变量,格式字符串里面有多少个占位符,就有多少个变量。

上面示例中,scanf()的第一个参数%d,表示用户输入的应该是一个整数。%d就是一个占位符,%是占位符的标志,d表示整数。第二个参数&i表示,将用户从键盘输入的整数存入变量i

注意,变量前面必须加上&运算符(指针变量除外),因为scanf()传递的不是值,而是地址,即将变量i的地址指向用户输入的值。如果这里的变量是指针变量(比如字符串变量),那就不用加&运算符。

下面是一次将键盘输入读入多个变量的例子。

scanf("%d%d%f%f", &i, &j, &x, &y);

上面示例中,格式字符串%d%d%f%f,表示用户输入的前两个是整数,后两个是浮点数,比如1 -20 3.4 -4.0e3。这四个值依次放入ijxy四个变量。

scanf()When processing numeric placeholders, whitespace characters, including spaces, tabs, newlines, etc., are automatically filtered. Therefore, one or more spaces between the data entered by the user will not affect scanf()the interpretation of the data. In addition, the user uses the Enter key to divide the input into several lines without affecting the interpretation.

1
-20
3.4
-4.0e3

In the above example, the user divides the input into four lines, and the result obtained is exactly the same as the input of one line. Every time you press the Enter key, scanf()it will start to interpret. If the first line matches the first placeholder, then the next time you press the Enter key, it will start to interpret from the second placeholder.

scanf()The principle of processing user input is that the user's input is put into the cache first, and after the Enter key is pressed, the cache is interpreted according to the placeholder. When interpreting user input, it will start from the first character left over from the last interpretation until the cache is read or the first character that does not meet the conditions is encountered.

int x;
float y;

// 用户输入 "    -13.45e12# 0"
scanf("%d", &x);
scanf("%f", &y);

In the above example, scanf()when reading user input, %dthe placeholder will ignore the leading space, -start to get data from there, and read until -13it stops, because the following characters .are not valid characters of integers. That is, the placeholders %dwill be read -13.

When calling for the second time scanf(), it will continue to read from the place where it stopped reading last time. The first character read this time is ., because the corresponding placeholder is %f, it will be read .45e12, which is a floating-point number format using scientific notation. The following #characters are not valid for floating-point numbers, so they will stop here.

Since scanf()multiple placeholders can be processed consecutively, the above example can also be written as follows.

scanf("%d%f", &x, &y);

scanf()The return value of is an integer indicating the number of variables successfully read. Returns if no items were read, or if the match failed 0. If the end of file is read, the constant EOF is returned.

Placeholder

scanf()The commonly used placeholders are as follows, which are printf()basically the same as the placeholders of .

  • %c:character.
  • %d: Integer.
  • %f: floattype float.
  • %lf: doubletype float.
  • %Lf: long doubletype float.
  • %s: String.
  • %[]%[0-9]: Specify a set of matching characters (for example ) in square brackets , and the matching will stop when encountering characters that are not in the set.

All of the above placeholders, except %c, automatically ignore leading whitespace characters. %cWhitespace characters are not ignored, and the current first character is always returned, whether it is a space or not. If you want to forcibly skip the blank characters before the character, you can write it scanf(" %c", &ch)as, that is, %cadd a space before it, which means skip zero or more blank characters.

Let's talk about placeholders in particular %s, which cannot simply be equivalent to strings. Its rule is to read from the current first non-blank character until it encounters a blank character (that is, a space, a newline, a tab, etc.). Cannot be used to read multiple words since %sit will not contain whitespace characters unless multiple %sare used together. This also means that it scanf()is not suitable for reading strings that may contain spaces, such as book titles or song titles. In addition, when a placeholder scanf()is encountered , a null character will be stored at the end of the string variable .%s\0

scanf()When reading a string into a character array, there is no check if the string exceeds the array length. Therefore, when storing strings, it is likely to exceed the boundaries of the array, resulting in unexpected results. In order to prevent this situation, %swhen using placeholders, you should specify the longest length of the read-in string, which is written as %[m]s, where [m]is an integer, indicating the maximum length of the read-in string, and the following characters will be discarded.

char name[11];
scanf("%10s", name);

In the above example, nameit is a character array with a length of 11. scanf()The placeholder %10sindicates that at most 10 characters input by the user can be read, and the following characters will be discarded, so that there is no risk of array overflow.

assignment omitter

Occasionally, user input may not conform to a predetermined format.

scanf("%d-%d-%d", &year, &month, &day);

In the above example, if the user enters 2020-01-01, the year, month, and day will be correctly interpreted. The problem is that the user may enter other formats, for example 2020/01/01, in which case scanf()parsing the data will fail.

To avoid this, scanf()an assignment suppression character is provided *. Just append *the percent sign to any placeholder, and that placeholder will not return a value and will be discarded after parsing.

scanf("%d%*c%d%*c%d", &year, &month, &day);

In the above example, %*cthe assignment ignore character is added after the percent sign of the placeholder *, indicating that this placeholder has no corresponding variable, and there is no need to return after interpretation.

sscanf()

sscanf()The function is scanf()very similar to , except that sscanf()it gets data from a string instead of user input. Its prototype is defined in the header file stdio.h.

int sscanf(const char* s, const char* format, ...);

sscanf()The first parameter of is a pointer to a string from which to get the data. Other parameters are scanf()the same as .

sscanf()It is mainly used to process strings read by other input functions and extract data from them.

fgets(str, sizeof(str), stdin);
sscanf(str, "%d%d", &i, &j);

In the above example, fgets()a line of data is first obtained from the standard input ( fgets()see the next chapter for details), and stored in a character array str. Then, extract two integers sscanf()from the string and put them in the variable and .strij

sscanf()One of the benefits of is that its data source is not streaming data, so it can be used repeatedly, unlike the scanf()data source of , which is streaming data, which can only be read once.

sscanf()The return value of is the number of variables that were successfully assigned, or the constant EOF if extraction fails.

getchar(),putchar()

(1)getchar()

getchar()The function returns a character entered by the user from the keyboard, when used without any parameters. When the program runs to this command, it will pause and wait for the user to input from the keyboard, which is equivalent to using scanf()the method to read a character. Its prototype is defined in the header file stdio.h.

char ch;
ch = getchar();

// 等同于
scanf("%c", &ch);

getchar()Leading whitespace characters are not ignored, and the first character currently read is always returned, whether it is a space or not. If the read fails, the constant EOF is returned. Since EOF is usually EOF -1, the type of the return value should be set to int instead of char.

Since getchar()it returns the characters read, it can be used in loop conditions.

while (getchar() != '\n')
  ;

\nIn the above example, the loop will exit only when the read character is equal to the newline character ( ), which is often used to skip a certain line. whileThe loop body of the loop has no statement, which means do nothing for the line.

The following example is to calculate the character length of a line.

int len = 0;
while(getchar() != '\n')
  len++;

In the above example, getchar()every time a character is read, the length variable lenwill increase by 1 until a newline character is read, which lenis the character length of the line.

The following example skips whitespace characters.

while ((ch = getchar()) == ' ')
  ;

In the example above, after the loop ends, the variable chis equal to the first non-space character.

(2)putchar()

putchar()The function outputs its argument character to the screen, equivalent to using printf()output a character. Its prototype is defined in the header file stdio.h.

putchar(ch);
// 等同于
printf("%c", ch);

When the operation is successful, putchar()the output character is returned, otherwise the constant EOF is returned.

(3) Summary

Since the usage of these two functions is simpler than and getchar(), and is usually implemented with macros, it is faster than and . If you operate a single character, it is recommended to use these two functions first.putchar()scanf()printf()scanf()printf()

puts()

puts()The function is used to display the parameter string on the screen (stdout), and automatically add a newline at the end of the string. Its prototype is defined in the header file stdio.h.

puts("Here are some messages:");
puts("Hello World");

In the above example, puts()two lines of content are output on the screen.

When writing is successful, puts()returns a non-negative integer, otherwise returns the constant EOF.

gets()

gets()The function was used to read the entire line of input from stdinthe slave, which has been abolished now, and is still introduced here.

This function reads a line of user input without skipping leading whitespace until a newline is encountered. This function discards the newline character, puts the remaining characters into the parameter variable, and appends a null character to the end of these characters \0to make it a string.

It is often puts()used in conjunction with .

char words[81];

puts("Enter a string, please");
gets(words);

The example above uses puts()prompts to output on the screen, and then uses gets()to get user input.

Since gets()the obtained string may exceed the maximum length of the character array variable, there is a security risk. It is recommended not to use it and use it instead fgets().

Guess you like

Origin blog.csdn.net/ALiLiLiYa/article/details/132128817