Problems related to 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.

 

 

Related Article

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.