The Magical scanf

Source: Internet
Author: User

The Magical scanf


As an important input function in the standard input and output function group, there is an important difference between the SCANF/SSCANF/VSCANF function and the printf/sprintf/vsprintf: if the format parameter does not match the following argument, The printf series function may cause the printed format or data not to be expected, while the SCANF series function may cause memory changes near the parameters to be entered, or even cause the program to crash, if the format parameter and subsequent parameters do not match.


Take the following function as an example:

8#include<stdio.h>

9#include<string.h>

10

11int Main (int argc, char * argv)

12{

-Char names[6];

+ char c= ' D ';

Short cnt=0x1234;

16

strcpy (names, "Hello");

18

printf ("Original values:\n");

printf ("cnt =%d, c =%c, names =%s\n", CNT, c,names);

21st

printf ("Please Input your settings:\n");

printf ("C =");

scanf ("%c", &c);

GetChar ();

-printf ("Names =");

scanf ("%s", names);

GetChar ();

printf ("Cnt =");

scanf ("%ld", &cnt);

GetChar ();

32

printf ("Latest values:\n");

printf ("cnt =%d, c =%c, names =%s\n", CNT, c,names);

35

return 0;

37}


The program expects to accept the character C from the standard input, the string names and the short type counter, and then prints the received input. However, if the program is fully tested, you will find that when the input CNT is negative or the input CNT value is relatively large, the final printed part of the value is found to be different from the input value, such as the following conditions:

[Email protected]cstudy]#./scan

Originalvalues:

Cnt= 4660, C = D, names = Hello

Pleaseinput Your settings:

C= h

names= Leifeng

Cnt=-2

Latestvalues:

Cnt=-2, c =, names = Leifeng

The root cause is that the SCANF series function writes data to the memory region corresponding to a pointer based on the format specified in the format string, rather than on the data type pointed to by the pointer. This often brings trouble and confusion to some programmers who have just come into the C language, and even programmers who have worked for years often overlook it. Therefore, it is necessary to have a clear understanding of the interface requirements and format parameters of scanf series functions.


Interface requirements for 1.SCANF series functions

The format parameter of the SCANF function specifies the type of data that is written to memory, including byte length, unsigned, integer, or floating-point. If the length of the data to be written to memory exceeds the length of the data type pointed to by the corresponding pointer, it overwrites the neighboring memory that the pointer points to the data, depending on the compiler's stack type (full decrement, full increment, empty decrement, null increment), hardware environment (large tail end and small tail end). For example, in the above example, the local variable CHARC is overwritten because the format string "ld" exceeds the length of the corresponding data shortcnt. Therefore, in order to avoid incorrect invocation of the scanf function, it may overwrite useful data and code, requiring that the data type pointed to by the pointer parameter following the format parameter must strictly conform to the type of data being entered.


Format string for 2.SCANF series functions

In general, the format string for the scanf function is similar to the format string for the printf series, which lists the commonly used format strings and their meanings:

H:half, used in front of d,i,o,u,x,x,n, denotes short, such as%HD, which represents shortint

Hh:half half, front char for d,i,o,u,x,x,n, representing Unsignedchar or Signedchar

J: Similar to H, but only used to modify intmax_t,uintmax_t

L:long, used to modify d,i,o,u,x,x, means to write data according to the memory pointed to by a pointer longint or Unsignedlong int. If it is used to modify the e,f,g, the input data will be read in double instead of float format

L:long long, which is used to modify d,i,o,u,x,x, to write data according to the memory pointed to by a pointer longlong int or unsignedlong long int. If it is used to modify the e,f,g, the input data will be read in longdouble instead of float/double format.

T: Represents ptridiff_t type, C99 introduced

Z: Represents the size_t type, C99 introduces

D: Indicates a signed decimal integer, int

I: If the input starts at 0x, 0X, the input data is read in 16, if start with 0, read in 8, and the other types are read in 10 binary.

o: unsigned 8 binary

U: unsigned 10 binary

x/x: unsigned 16 binary

F/E/G/E/A: Signed floating point

P: pointer type

S: Enough space for the string to automatically add '% ' to the end of the input

C: A sequence of characters with a default length of 1

[: Specifies the range of characters in a non-empty string sequence

M: String, the SCANF series function automatically applies space based on the length of data entered, and the caller takes care to release


An example of the full use of the format character M and [] is given below:

Char*p;

Intn


errno= 0;

n= scanf ("%m[a-z]", &p);

if (n = = 1) {

printf ("read:%s\n", p);

Free (p);

}else if (errno! = 0) {

Perror ("scanf");

}else {

fprintf (stderr, "No matching characters\n");

}


Reference: Scanfman Handbook

This article is from the "Store Chef" blog, so be sure to keep this source http://xiamachao.blog.51cto.com/10580956/1764839

The Magical 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.