//------------------------------------------------ // File: width.cpp // Author: D. Frey // // Section: 1234 // Project: none // Description // This program shows the effect of the setw( ) // manipulator //------------------------------------------------ #include #include #include using namespace std; int main ( ) { string name = "John Q. Public"; int nameSize = name.size(); int width; cout << "String Width Tests" << endl; cout << "------------------" << endl << endl; cout << "Using manipulator setw( )" << endl; cout << "-------------------------" << endl; // smaller than length of "name" << endl; width = nameSize - 5; cout << "width = " << width << " cout << "Name:" << setw( width ) << name << endl << endl; // exactly the same as length of "name" << endl; width = nameSize; cout << "width = " << width << " cout << "Name:" << setw( width ) << name << endl << endl; // bigger than the length of the name" << endl; width = nameSize + 5; cout << "width = " << width << " cout << "Name:" << setw( width ) << name << endl; // same test using cout.width() cout << endl; cout << "Using cout.width( )" << endl; cout << "-----------------------" << endl; // width too small?? width = nameSize - 5; cout << "width = " << width << endl; cout << "Name:"; cout.width( width ); cout << name << endl; // width just right width = nameSize; cout << "width = " << width << endl; cout << "Name:"; cout.width( width ); cout << name << endl; // width too big width = nameSize + 5; cout << "width = " << width << endl; cout << "Name:"; cout.width( width ); cout << name << endl; cout << endl; // numeric width test cout << "Numeric width test" << endl; cout << "------------------" << endl; double PI = 3.141596; int age = 42; cout << "width not set (default = 6)" << endl; cout << "Age = " << age << endl; cout << "Pi = " << PI << endl; cout << "width = 1" << endl; cout << "Age = " << setw( 1 ) << age << endl; cout << "Pi = " << setw( 1 ) << PI << endl; cout << "width = 10" << endl; cout << "Age = " << setw( 10 ) << age << endl; cout << "Pi = " << setw( 10 ) << PI << endl; return 0; }