C Program Learning Diary--char string and integer, floating-point data conversion to each other

Source: Internet
Author: User
The char string is converted to a number of integers, and of course only the strings are stored with ' 0 ' ~ ' 9 ' characters, typically using the Atoi function:
#include <stdlib.h>
int atoi (const char *nptr);//The number of integers after conversion

and integral type, there are two ways to convert a floating-point number to a string: one is a function implementation, the other is a format output; The function implementation method is relatively tedious, you can use the itoa () function, but the function cannot be ported, and another way is recommended--format output:
#include <stdio.h>
int sprintf (char *str, const char *format, ...);
int snprintf (char *str, size_t size, const char *format, ...);

The above two methods are relatively simple to implement:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
     Char BUF[20];
     Double pi = 3.1415926
     memset (buf, 0, sizeof (BUF));
     sprintf (buf, "%.7LF", pi); Floating-point data defaults to only 6 digits after the decimal point, where the number of digits written is specified
     printf ("%s\n", buf);
 
     return 0;
}

This method allows a floating-point data to be converted to a string, while snprintf () is the number of bytes that need to be added to the floating-point data in the BUF.

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.