Hi guys. So the problem I'm having is that when you enter a value for the radius (rad) variable the cursor wants to work its way from the left to the right when the user types resulting in double digit numbers being longer than the output columns.
It looks like this when the program runs and you enter anything longer than one digit:
1 2 3
Enter radius for the sphere: 17
Surface area of the sphere: 3631.67804 (1156π)
The volume of the sphere: 20579.50889 (19652π/3)
I would like the 7 to line up with the column below it. I tried setting the width to one less than I had before & single digits end up one space too far to the left like so:
1 2 3
Enter radius for the sphere: 4
Surface area of the sphere: 201.06176 (64π)
The volume of the sphere: 268.08235 (256π/3)
I'd like the cursor to fill in the digits starting on the right and push the numbers entered to the left OR just a fix to justify the output columns for however many digits I enter. Something like that anyways. Thanks a bunch in advance.
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
constdouble PI = 3.14159;
double rad = 0;
double area = 0;
double vol = 0;
int areaPi = 0;
int volPi = 0;
// I rearranged these, but only for "thinking" purposes:
// 'left' is a permanent modifier -- it affects every subsequent thing that gets printed
// 'setw' is a temporary modifier -- it only affects the very next thing that gets printed
//
// I personally find it more readable (and logical) to stick things
// that modify the next argument without any interleaving things.
cout << left << setw(38) << "Enter radius for the sphere: ";
// Here, we'll get the input as a string (so we can KNOW its width) and convert it to a usable value (double)
// You may also wish to add some error handling (stod() will throw an exception if s cannot be converted)
string s;
getline( cin, s );
rad = stod( s );
// Here's our total line width
int linewidth = 38 + s.length();
// Calculations from the input
area = (4 * PI * (rad * rad));
vol = ((4.0/3.0) * PI * (rad * rad * rad));
areaPi = (4 * (rad *rad));
volPi = (4 * (rad * rad * rad));
// Here we set a few of the permanent formatting modifiers for printing stuff
cout << setprecision(5) << fixed << right;
// Now we can carefully format the output lines
string surface_area_of_sphere = "Surface area of the sphere: ";
cout << surface_area_of_sphere << setw(linewidth-surface_area_of_sphere.length()) << area << " (" << areaPi << "π)\n";
string volume_of_sphere = "Volume of the sphere: ";
cout << volume_of_sphere << setw(linewidth-volume_of_sphere.length()) << vol << " (" << volPi << "π/3)\n";
return 0;
}