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:
#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.