Detailed explanation of scanf function (nanny-level explanation) and details that need to be paid attention to when using it

Table of contents

1. Definition of scanf function:

2. Related information about scanf function 

1. Function:

 2. Call format:

 3.scanf function character control string:

4. Common format specifiers:

 5.The return value of the scanf function:

3. Issues that need to be paid attention to when using the scanf function (key points)

Question 1: How to make the scanf() function correctly accept strings with spaces? Such as: I love you!

Problem 2: Problem with residual information in keyboard buffer

Question 3: How to deal with program deadlock or errors caused by incorrect input in the scanf() function

4. Regarding the development of scanf function:

5. Summary:


1. Definition of scanf function:

scanf() is an input function in C language. Like the printf function, it is declared in the header file stdio.h, so #include < stdio.h > should be added when using the scanf function . (In some implementations, the printf function and scanf function can be used without using precompiled commands) It is a format input function , that is, inputting data from the keyboard into the specified variable according to the user-specified format .

(The picture below is from the explanation of the scanf function in cplusplus.com) 

2. Related information about scanf function 

1. Function:

        Perform formatted input

 2. Call format:

        scanf("<formatted string>",<address table>);

 3.scanf function character control string:

        1. Format specifier;

        2. Blank characters;

        3. Non-white characters, except formatting specifier (%);

4. Common format specifiers:

 5.The return value of the scanf function:

        First, the scanf function returns int type data. The scanf function returns the number of data items successfully read. If an "end of file" is encountered when reading data, it returns EOF.

example:

scanf("%d %d",&a,&b);

If both a and b are read successfully, return 2.

If only a is successfully read, the return value is 1;
if a fails to be read, the return value is 0;
if an error or end of file is encountered, the return value is EOF. The end of file is Ctrl+z or Ctrl+d.

3. Issues that need to be paid attention to when using the scanf function ( key points )

Question 1: How to make the scanf() function correctly accept strings with spaces? Such as: I love you!

#include <stdio.h>
 
int main()
 
{
 
    char str[80];
     
    scanf("%s",str);
 
    printf("%s",str);
     
    return 0;
 
}

enter:

I love you

Output:

I

The above procedure does not achieve the intended purpose. Because scanf scans the space after "I", it considers that the scanning of str is over (the space is not scanned), and ignores the following "love you!". It is worth noting that we change the above program to verify:

#include<stdio.h>
 
#include<windows.h>
 
int main(void)
 
{
 
    char str[80],str1[80],str2[80];
     
    scanf("%s",str);/*此处输入:I love you!*/
 
    printf("%s\n",str);
 
    Sleep(5000);/*这里等待5秒,告诉你程序运行到什么地方*/
     
    /**
 
    *不是sleep(5)
 
    *1,函数名是Sleep不是sleep。
         *
    2,Windows API中,unsigned Sleep(unsigned)应该是毫秒ms.
 
    */
 
    scanf("%s",str1);/*这两句无需你再输入,是对stdin流再扫描*/
     
    scanf("%s",str2);/*这两句无需你再输入,是对stdin流再扫描*/
 
    printf("%s\n",str1);
     
    printf("%s\n",str2);
 
    return 0;
 
}

enter:

I love you!

Output:

I 
love 
you!

So the conclusion is: the residual information love you exists in the stdin stream, not in the keyboard buffer . So can the scanf() function complete this task? The answer is: yes! Don’t forget that the scanf() function also has a %[] format control character. Please see the following program:

#include<stdio.h>

int main()
{
    char str[50];
    scanf("%[^\n]",str);/*scanf("%s",string);不能接收空格符*/
    printf("%s\n",str);
    return 0;
}

By using scanf("%[^\n]",str), you can effectively solve the problem of spaces in the input string.

Problem 2: Problem with residual information in keyboard buffer

#include<stdio.h>

int main(void)
{
    int a;
    char c;
    while(c!='N')
    {
    scanf("%d",&a);
    scanf("%c",&c);
    printf("a=%dc=%c\n",a,c);
    /*printf("c=%d\n",c);*/
    }
    return 0;
}

After running this code, we can find that scanf("%c",&c) does not perform the operation of assigning a value to c well. For this phenomenon, we can enable printf("%d",c). After troubleshooting, we can find that the output value is 10, and the ASCII value corresponding to 10 is "\n", which is the ENTER line break character. Therefore, we can explain it this way: when the scanf function of input a has finished reading, ENTER Directly assigned to c. To deal with this problem, we need to clean the input buffer so that we can correctly assign values ​​to C.

For this we can use the getchar() function to clean up the newline characters.

getcahr();

Or directly use the fflush(stdin) function to clean the input buffer

#include<stdio.h>

int main(void)
{
    int a;
    char c;
    while(c!='N')
    {
        scanf("%d",&a);
        fflush(stdin);
        scanf("%c",&c);
        fflush(stdin);
        printf("a=%dc=%c\n",a,c);    
    }
    return 0;
}

Question 3: How to deal with program deadlock or errors caused by incorrect input in the scanf() function

#include<stdio.h>

int main(void)
{
    int a,b,c;
    scanf("%d,%d",&a,&b);
    c=a+b;/*计算a+b*/
    printf("%d+%d=%d",a,b,c);
    return 0;
}

In the above program, if the values ​​​​of a and b are entered correctly, there will be no problem. However, you cannot guarantee that the user can enter it correctly every time. Once the wrong type is entered, an incorrect result will be obtained. Haha, this may all happen It’s a problem everyone has encountered, right? Solution: When the scanf() function is executed successfully, the return value is the number of successfully read variables. In other words, your scanf() function has several variables. If the scanf() function reads all the variables normally, it will return how many variables it has. . But there is another issue to note here. If illegal data is entered, there may be residual information in the keyboard buffer. Correct routine:

#include<stdio.h>

int main(void)
{
    int a,b,c;
    while(scanf("%d%d",&a,&b)!=2)
    fflush(stdin);
    c=a+b;
    printf("%d+%d=%d",a,b,c);
    return 0;
}

4. Regarding the development of scanf function:

When using the scanf function for input, you must specify the type and format of the input data, which is not only cumbersome and complicated, but also error-prone. C++ retains scanf only for compatibility with C, so that programs written in C language in the past can run in the C++ environment. C++ programmers are willing to use cin for input and rarely use scanf. But scanf has an obvious advantage, it is faster than the cin function.

5. Summary:

Regarding the related introduction and explanation of the scanf function, if there are any flaws or omissions, please point them out in the comment area. I would like to express my gratitude again. Thank you to every guest who has read this article.

Guess you like

Origin blog.csdn.net/2201_75998194/article/details/130911910