-
Simple Question(maybe)
Im doing a small thing for school, and i want to make a program to have you enter a number, and have it count the digits, and then tell you how many digits there are.
I only know a little C++, and would like to know how to go about haveing it count the digits. thanks for anyone who helps.
-
Hmm you could either input the numbers in a string and find the strings length. Or you could do a little checking.
like if its less than 10 then its 1 digit... less the 100 and greater than or equal to 10 then 2 digits.
-
The first idea is what i was thinking i believe, because if i did the second one, its almost an infinite list.
Now how would i go about doing that. Quick example (anyone)?
-
Simple formula:
# of base b digits in n = floor(log{b}(n)) + 1 (where log{b}(n) means log base b of n)
-
It can't be an infinite list because the variables are only able to hold a number so large... But the string route is a good approach. try sprintf, that'll get you what you want.
PK
-
-
Using a for loop along with the / operator might be more appropriate for learning.
-
If you include the header file <string>, you can make a string using the variable type std::string; and if you include the header file <cstring>, you can find the length of a string using the strlen(name_of_std::string_var) if that is helpful.....
-
C++Child, you can find the length of a std::string using its length() or size() function, and you don't need <cstring> to do that.
Code:
std::string name_of_stdstring_var("fifteen letters");
int fifteen = name_of_stdstring_var.length();
The strlen function in <cstring> applies to C-style, null terminated character arrays, not std::string.
-
Thank you jlou, I didn't know that. I usually append my strings with '\0' anyways.
-
STL strings are null terminated as well. Under the hood STL strings have the same null terminated char array as in a C style strings, they are just hidden behind an interface that makes them easiert to be manipulated.