Talk C Chestnut Bar (38th: C-language example-do you know scanf?)

Source: Internet
Author: User

Ladies and gentlemen, crossing, we are talking about the example of getting the current date and time, and this is the example of the library function in the C language: scanf. Gossip Hugh, words return to the positive. Let's talk C chestnuts together!

Crossing, speaking of library functions in C : scanf, I think everyone knows it and know it's used to get input from standard input (which can be used as a terminal), but I guess most people don't know much about the function , Then I'll tell you the little details.

The scanf function has a return value

When you normally use the scanf function, you get the input value from the terminal, for example: scanf ("%d", &a) takes a value of type int from the terminal and saves the value in variable a. Everybody ignores it. There is also a return value of type int, which represents the number of scanf read from the terminal, such as: scanf ("%d", &a) returns a value of 1. If it returns 0, the read value from the terminal fails. Therefore, when we write the program, it is better to judge the return value of scanf , by the return value to confirm whether to successfully read the value from the terminal, which can improve the robustness of the program. For example: if (1!=scanf ("%d", &a)) exit (0);

Let's give a practical example to illustrate:

//相信大家都能看明白,因此main等相关的内容就不写出来了printf("Please input a number,ex: 3 \n");if(1scanf("%d"// confirm the inputting option{    printf("Can‘t get the number \n");    return1;}else    printf("get the number %d normally \n",iVal);

The following results can be obtained after compiling and running the program:

anumber32                 //手动输入数字2getthenumber2

As you can see from the running results of the program, the program runs into the Else branch, which means that scanf returns the value 1. and the number 2 that we entered in the terminal is stored in the variable ival.

scanf function Gets the advantages and disadvantages of the input content

The first parameter of the SCANF function is used to control the format, and it can control the type of the read value, such as the use of%d when reading a numeric value of type int. This function, I will not say, I believe most of the crossing know, and may even be like Motoyama uncle's slogan: The earth people know. Ha ha.

Another function of this is to control the format of the input values, such as scanf ("%d", &a) Note: There is a space character after D, which indicates that the value of the int type is obtained from the terminal until non-whitespace characters are encountered . The whitespace characters here include spaces, tab keys, and line breaks.

Let's give a practical example to illustrate:

printf("Please input a number,ex: 3 \n");if(1 != scanf("%d "%d{    printf("Can‘t get the number \n");    return1;}else    printf("get the number %d normally \n",iVal);

The following results can be obtained after compiling and running the program:

anumber36   //手动输入数字6,这时程序没有停止,它还在等待获取非空白字符7   //再次输入非空白字符,也就是数字7,程序才结束getthenumber6

Everyone, I have written in the comments, I believe we can see the principle of the understanding. You may ask, which of the numbers you have just entered is 7? In fact, it is still in the input buffer, if the program below just write the following program:

scanf("%d",&iVal)printf("get the number %d normally \n",iVal);

It will get the following results:

getthenumber7 //从输入缓冲区中获取数字,并且存放在变量iVal中

Crossing question: If you move the space in the above example to the front of%d , that is scanf ("%d", &ival), what does that mean? it has the same meaning as without a space . In other words: scanf ("%d", &ival) and scanf ("%d", &ival) have the same effect, and we illustrate by practical examples:

printf("Please input a number,ex: 3 \n");if(1 != scanf(" %d",&iVal)) //  %d{    printf("Can‘t get the number \n");    return1;}else    printf("get the number %d normally \n",iVal);

The following results can be obtained after compiling and running the program:

anumber36   //手动输入数字6,这时程序停止,输出运行结果。它不会像上面的例子中等待获取非空白字符getthenumber6

In fact, thescanf function itself has the function of filtering whitespace , which reads a number or character from the terminal until it encounters a non-whitespace number or character, so we do not need to include a space in its first argument unless there is a specific need. It is wrong to think that it is possible to filter whitespace by adding a space.

Let's give an example:

printf("Please input 3 number,ex: 3 \n");if(3 != scanf("%d%d%d",&iVal,&a,&b)) // confirm the inputting option{    printf("Can‘t get the number \n");    return1;}elseprintf("get the number %d %d %d normally \n",iVal,a,b);

The following results can be obtained after compiling and running the program:

3number3  78   //手动输入数字7和8,在7前面和后面都有空格,scanf自动过滤它们,等待输入第三个数字9      //输入8后按下回车,然后输入第三个数字9。回车也是一种空白符,所以被scanf过滤掉了, 直到输入9它才结束getthenumber789

Everyone, I have written in the comments, I believe we can see the principle of the understanding.

The ability of the scanf function to automatically filter out whitespace is considered an advantage , but there are some side effects of this function as a disadvantage. For example, after getting the value of a non-character type such as int or float, it puts the carriage return followed by these values into the input buffer , and then uses scanf or other input functions (such as GetChar) to get the numeric value of the character type and finds the carriage return. Let's give an example to illustrate:

GetintValue firstlyprintf("Please input a number,ex:3 \ n");if(1! = scanf ("%d", &ival)//confirm the inputting option{printf("Can ' t get the number \ n");return 1;}Else    printf("Get the number %d normally \ n", ival);//Get Char Value secondlyprintf("Please input a char ex:a \ n");if(1! = scanf ("%c", &ch)//confirm the inputting option{printf("Can ' t get the number \ n");return 1;}Else    printf("Get the number %c<==>%d normally \ n", ch,ch);

The following results can be obtained after compiling and running the program:

anumber34     //输入数字4,然后回车getthenumber4acharagetthenumber     //我都没有输入字符,它就自动读取了4后面的回车符,并且显示回车<==>10 normally    //回车符不太直观,所以我显示了它的的ASII码

Everyone, I have written in the comments, I believe we can see the principle of the understanding. In addition, you can check the Asii code table, through the table can be found to find the Asii code is 10.

scanf function causes buffer overflow

there is a risk of buffer overflow when getting a string using scanf . For example, scanf ("%s", array) means getting a string from the terminal and storing the obtained string in an array of arrays. Have crossing ever wondered what would happen if the user entered a string longer than the array's capacity. I can tell you that this time there is a serious problem: buffer overflow .

Is there a way to allow the user to enter a string that is less than the array size? This is a bit difficult, because the user wants to enter what content, we have no way to know, and also can not prevent the user input too long string ah. What to do? We can manually specify the length of the scanf read-in string by modifying the first parameter of the scanf, which ensures that the length of the string scanf from the terminal is smaller than the capacity of the array, thus avoiding a buffer overflow.

Let's give a practical example:

// be carefull for overfollowprintf("Please input a string ex: hello  \n");if(scanf("%7s",array1// confirm the inputting option, 1 means 1 string{    printf("there is a voerfollow \n");    return1;}else    printf("get the string %s \n",array);

The following results can be obtained after compiling and running the program:

astring ex: hello  123456789 //在终端中输入长度为9的字符串getthestring1234567  

Crossing, we have modified the first parameter of scanf:%s==>%7s, which means to read a string of length 7 . From the running results of the program, SCANF is exactly the first 7 characters in the string that were read from the terminal as we requested. This avoids buffer overflow and improves the robustness of the program.

Crossing, we in the text in order to illustrate the principle of scanf function, the code is very scattered, the complete code in my resources, you can click here to download the use.

Crossing, do you know the "you understand scanf" example, we are here, hope that after we finish this chapter, we can understand the scanf function more deeply. I want to know what the following example, and listen to tell.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Talk C Chestnut Bar (38th: C-language example-do you know scanf?)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.