Problems caused by printing float with sprintf and controlling the number of decimal places

Source: Internet
Author: User

Recently, I found a bug in my project and killed the process. I checked it and found it was the most inconspicuous place. I will record it here.

First look at the following code

# Include <iostream> # include <stdio. h> using namespace STD; int main () {char AA [1024] = {0}; float F = 50.123456; // the intention is to output a floating point number to a string, the number of decimal places is two. sprintf (AA, "% 0. * F ", f); printf (" % F \ n ", f); cout <AA <Endl; sprintf (AA," % 0. * F ", 2, F); cout <AA <Endl; cout <" Hello world! "<Endl; return 0 ;}

 

The running result is as follows:

 

In the code, sprintf (AA, "% 0. * F ", f); you want to output a floating point number to a string and control the number of digits after the decimal point. However, if you do not specify the number of decimal places, as a result, sprintf prints a long string of data to the variable AA. When the space of AA is insufficient, the array will be out of bounds, resulting in program crash. This is the reason for the process being killed in the project. As for how the sprintf function prints such a long string of data, wait for the source code to be analyzed.

 

 

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.