Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C++, wrong result in the counting of the number of digits, converting to string and using .length()

I need to count the number of digits in an integer number.

My approach is to turn the number into a string, and then count the characters in the string.

I have the correct result if I do this "step by step", with intermediate variables:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <string>

float videoLengthMs = 123456;

int cielo = std::ceil(videoLengthMs);

std::string pippo = (std::to_string(cielo));

int charnm = pippo.length();

but if I try to compute it all at once, I have the wrong result:

#include <string>

float videoLengthMs = 123456;

int charnm = (std::to_string(std::ceil(videoLengthMs))).length();

I am novice in C++, and I think I am doing something wrong with the syntax, but I can’t see what is it.

(N.B. here for consistency I have defined the variable videoLengthMs, as a float; in my code this variable is the result of a division, and this is the reason why I consider it a float and I compute the ceiling first)

>Solution :

The result if std::ceil(videoLengthMs) is a float.
In the first version, you store that result in an int, truncating it.
In the second version, you pass the float value directly to std::to_string, which results in "123456.000000", which is of course a lot longer than the string "123456" that you get from the int value. You can cast the result of std::ceil to an int for the same result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading