Re: Accelerated C++ exercise 4-2 -- converting int to string?
On Jul 27, 6:23 pm, banangroda <fredrik...@gmail.com> wrote:
Here's the question and the code I wrote for it. The // comment
represents what I would like to do. Is there a really crude way of
doing that -- because the book hasn't provided any fancy methods of
doing it such as string streams, type casting, or anything like that
-- or would you suggest a different approach?
/*
4-3. What happens if we rewrite the previous program to allow values
up to
but not including 1000 but neglect to change the arguments to setw?
Rewrite
the program to be more robust in the face of changes that allow i to
grow
without adjusting the setw arguments.
*/
#include <iomanip>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::setw;
using std::string;
int main() {
int from = 1;
int up_to = 1000;
// int pad = length of up_to
// int pad_square = length of (up_to * up_to)
cout << setw(pad) << "Value:" << setw(pad) << "Square:" << endl;
for (; from < up_to; ++from) {
cout << setw(pad) << from << setw(pad) << from * from << endl;
}
}
Not very polished, but as an indicative approach you might find this
helpful:
// length of positive int
template <int N>
struct Length_Of_Positive
{
static const int value = 1 + Length_Of_Positive<N / 10>::value;
};
template<>
struct Length_Of_Positive<0>
{
static const int value = 0;
};
#include <iostream>
using namespace std;
int main()
{
cout << Length_Of_Positive<1>::value << '\n';
cout << Length_Of_Positive<9>::value << '\n';
cout << Length_Of_Positive<10>::value << '\n';
cout << Length_Of_Positive<99>::value << '\n';
cout << Length_Of_Positive<100>::value << '\n';
cout << Length_Of_Positive<999>::value << '\n';
cout << Length_Of_Positive<1000>::value << '\n';
cout << Length_Of_Positive<9999>::value << '\n';
}
Cheers,
Tony
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]