ITOA, atoi, sprintf, and printf usage

Source: Internet
Author: User
Tags 04x print format
Functions of ITOA and atoi functions in C ++

ITOA

Function: converts an integer to a string.
Usage: char * ITOA (INT value, char * string, int Radix );
Description: ITOA is the abbreviation of the English integer to array (converting the int integer into a string and saving the value in the array string. value indicates the integer to be converted, and Radix indicates the base number, that is, the value is first converted to the base number of Radix, and then saved in the string.
Note: The header file of this function is "stdlib. H"
Program example:
# Include <stdlib. h>
# Include <stdio. h>
Int main (){
Int number = 123456;
Char string [25];
ITOA (number, String, 10 );
Printf ("integer = % d string = % s \ n", number, string );
Return 0;
}

Note: The compilation system is VC ++ 6.0, which is not supported by TC.

Atoi

Function Name: atoi
Function: converts a string to an integer.
Function Description: atoi () scans the nptr parameter string and starts type conversion when the first number or positive or negative sign is detected. After that, the conversion is stopped when the non-number or Terminator \ 0 is detected, returns the integer number.
Usage: int atoi (const char * nptr );
Header file: # include <stdlib. h>
Program example:
1)
# Include <stdlib. h>
# Include <stdio. h>

Int main (void)
{
Int N;
Char * STR = "12345.67 ";

N = atoi (STR );
Printf ("string = % s integer = % d \ n", STR, N );
Return 0;
}
Execution result
String = 12345.67 integer = 12345

2)
# Include <stdlib. h>
# Include <stdio. h>
Int Mian ()
{
Char A [] = "-100 ";
Char B [] = "123 ";
Int C;
C = atoi (A) + atoi (B );
Printf ("c = % d \ n", C );
Return 0;
}
Execution result
C = 23

 

 

Sprintf and snprintf usage (can be used as a supplement to the ITOA function in Linux)

Sprintf () format the output function (image)
Function: sprintf () is used for formatting output.
Usage: This function is called in int sprintf (char * string, char * format, arg_list );
Description: The usage of the sprintf () function is the same as that of the printf () function, except that the sprintf () function provides the first parameter string (generally a character array), and then calls outtextxy () the function displays the characters in the string on the screen. Arg_list is a parameter table, which can be an indefinite number. When outputting a number in plotting mode, you can use the sprintf () function to send the output format to the first parameter and then display the output.

Function Name: sprintf
Function: Send formatted output to a string.
Usage: int sprintf (char * string, char * farmat [, argument,...]);

Snprintf () is an expression that limits the number of characters in sprintf ().

Snpirntf (char * string, size_t N, char * format, arg_list); // n of the red font indicates that the first n characters are input to the string from the format.

Program example:

 1 #i nclude 2 #i nclude 3  4 int main(void) 5 { 6 char buffer[80]; 7  8 sprintf(buffer, "An approximation of Pi is %f\n", M_PI); 9 puts(buffer);10 return 0;11 }

Sprintf outputs a formatted string to a destination string, while printf outputs a formatted string to the screen. The first parameter of sprintf should be the target string. If this parameter is not specified, a message "this program produces an illegal operation and is about to be closed..." appears during execution.
Because the C language does not check whether the space of the string is large enough during string operations, the program may crash because the array is out of bounds. Even if it happens that the program does not go wrong, do not use it as it goes wrong in the morning or evening. Therefore, you must allocate enough space to the Buf before calling sprintf.

Since sprintf and printf are almost the same in usage, but the printing destination is different, the former is printed to the string,
The latter is output directly on the command line. This also makes sprintf much more useful than printf. So this article focuses on sprintf, sometimes
It is also interspersed with pritnf.
Sprintf is a variable parameter function, which is defined as follows:
Int sprintf (char * buffer, const char * Format [, argument]...);
In addition to the fixed types of the first two parameters, you can take over multiple parameters later. But its essence is obviously in the second parameter:
Format the string.
Both printf and sprintf use formatted strings to specify the string format. Some strings starting with "%" are used inside the format string.
Format specifications
The function replaces the specifier with the variable at the corresponding position to generate a string that the caller wants.
Format a numeric string
One of the most common applications of sprintf is to print Integers to strings. Therefore, spritnf can be replaced in most cases.
ITOA. For example:
// Print the integer 123 into a string and save it in S.
Sprintf (S, "% d", 123); // generate "123"
You can specify the width. If the width is insufficient, spaces are filled on the left:
Sprintf (S, "% 8d % 8d", 123,456 7); // generate: "123 4567"
Of course, you can also align left:
Sprintf (S, "%-8d % 8d", 123,456 7); // generate: "123 4567"
You can also print the data in hexadecimal format:
Sprintf (S, "% 8x", 4567); // lowercase hexadecimal notation, with 8 width positions and right alignment
Sprintf (S, "%-8x", 4568); // in hexadecimal notation, the width occupies 8 positions and is left aligned.

In this way, the hexadecimal string of an integer is easy to obtain, but when we print the hexadecimal content, we usually want
In the left side of the fill 0 equal width format, then how to do it? Simply add 0 to the number that represents the width.
Sprintf (S, "% 08x", 4567); // generate: "201711d7"
You can also use this left-side 0 Complement Method to print the 10-in-hexadecimal format with "% d" above.
Pay attention to a symbol extension problem: for example, if we want to print the short INTEGER (short)-1 memory 16 into tabulation
Format: On the Win32 platform, a short type occupies 2 bytes, So we naturally want to use 4 hexadecimal numbers
Print it:
Short Si =-1;
Sprintf (S, "% 04x", Si );
Why is "ffffffff" generated? Because spritnf is a variable parameter function, in addition to the first two parameters
The parameters are not of type security, and the function cannot simply use "% x" to know that the parameter pressure stack before the function is called.
Is it a 4-byte integer or a 2-byte short integer, so a unified 4-byte processing method is adopted,
As a result, the parameter is expanded to a 32-bit integer-1 when the stack is pressed. If the four locations are insufficient, the 32-bit integer is used.
-The 8-digit and 16-digit of 1 are printed. If you want to see the original form of Si, you should let the compiler implement 0 extension instead
Symbol extension (when expansion is performed, the left side of the binary complement 0 instead of the complement sign bit ):
Sprintf (S, "% 04x", (unsigned short) Si );
You can. Or:
Unsigned short Si =-1;
Sprintf (S, "% 04x", Si );
Sprintf and printf can also print integer strings in octal, using "% O ". Note that both hexadecimal and hexadecimal are not supported.
Negative numbers are all unsigned. In fact, they are directly hexadecimal or octal representation of the internal code of the variable.
Control floating point print format
The printing and format control of floating point numbers is another common function of sprintf. Floating Point Numbers are controlled by the format character "% F", which is guaranteed by default.
Keep the six digits after the decimal point, for example:
Sprintf (S, "% F", 3.1415926); // generate "3.141593"
But sometimes we want to control the print width and decimal places, then we should use the format "% m. NF", where the M Table
The print width. N indicates the number of digits after the decimal point. For example:
Sprintf (S, "% 10.3f", 3.1415626); // generate: "3.142"
Sprintf (S, "%-10.3f", 3.1415626); // generate: "3.142"
Sprintf (S, "%. 3f", 3.1415626); // The total width is not specified, resulting in: "3.142"
Pay attention to one question, you guess
Int I = 100;
Sprintf (S, "%. 2f", I );
What will it do? 100.00 "? Right? Try it on your own and try the following:
Sprintf (S, "%. 2f", (double) I );
The first one is definitely not the correct result. The reason is as mentioned above. When the parameter is pressed to the stack, the caller does not know
The corresponding format controller is "% F ". When a function is executed, the function itself does not know that the number pushed to the stack in the current year is an integer,
So the four bytes that saved the integer I were forcibly interpreted as a floating-point number.
However, if someone is interested in manually encoding a floating point number, you can use this method to check your hand
Is the orchestration result correct .?
Character/ASCII code comparison
We know that in C/C ++, char is also a common scalable type, in addition to the word length, it corresponds to short,
There is no essential difference between int and long types, but they are used to representing characters and strings. (Maybe we should
This type is called "byte", and now we can use byte or short to set char through typedef according to the actual situation.
)
Therefore, print a character using "% d" or "% x" to obtain its 10-or 16-digit ASCII code.
To print an integer using "% C", you can see its ASCII characters. The following section describes
The ASCII code table is printed on the screen (printf is used here. Note that "#" and "% x" are automatically used to add "0x" to the hexadecimal number"
Prefix ):
For (INT I = 32; I <127; I ++ ){
Printf ("[% C]: % 3d 0x % # 04x \ n", I, I );
}
Connection string
Since the sprintf format control string can insert a variety of things, and finally "connect them into a string", it will naturally be able to connect
Concatenates strings to replace strcat in many cases, but sprintf can connect multiple strings at a time (it can also
Insert other content among them, which is flexible in short ). For example:
Char * Who = "I

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.