Is there a short way to determine how many digits are in an integer? I'm new to C++, and writing a program that's supposed to a number in one column, and its square in the next. I'm using setw to manipulate the width of the coulms.
Here is those code:
#include <iostream>
#include <iomanip>
using std::cout; using std::setw; using std::streamsize;
int main()
{
const int MAX = 100;
for (int i = 0; i != MAX;++i)
{
cout << setw(2) << i << setw(5) << i * i << std::endl;
}
}
This works fine as is, but when I change MAX to 1000, the output gets screwed. I know it's because neither column is wide enough to hold the output, so they get jammed together. I want to make the program robust, so that the output would scale to accomodate shrinking and growing MAX.
I have an idea that if I can do something like this it would work:
#include <iostream>
#include <iomanip>
using std::cout; using std::setw; using std::streamsize;
int main()
{
const int MAX = 100;
for (int i = 0; i != MAX;++i)
{
int square = i * i;
cout << setw(length_of_i) << i << setw(length_of_square) << square << std::endl;
}
}
Thoughts?