4-2
Write a program to calculate the squares of int values up to 100. The program should write two columns: The first lists the value; the second contains the square of that value. Use setw (described above) to manage the output so that the values line up in columns.
#include <iostream>
#include <vector>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
int main()
{
vector<int>origin;
vector<int>calculated;
typedef vector<int>::size_type counts_sz;
int data;
int data_len;
int maxlen = 0;
cout << "input data:" << endl;
// read all data and write down the maxlen
while (cin>>data)
{
origin.push_back(data);
calculated.push_back(data*data);
data_len = 1;
while ((data /= 10) > 0)
{
data_len++;
}
maxlen = maxlen > data_len ? maxlen : data_len;
cout << "input next:" << endl;
}
// display all data
for (counts_sz i = 0; i != origin.size(); i++)
{
data_len = 1;
data = origin[i];
while ((data /= 10) > 0)
{
data_len++;
}
cout << origin[i]
<< string(maxlen + 1 - data_len, ' ')
<< calculated[i]
<< endl;
}
system("pause");
}