第六回:基本輸入與輸出

 

串流輸出

 

串流輸入

 

格式化輸出

Example:
    #include <cstdlib>
    #include <iostream>
    #include <iomanip>

    using namespace std;

    int main(int argc, char *argv[])
    {
        int k;
        cout << "Print 1 to 100 formatted by setw() :" << endl; 
        k = 1;
        for (int i = 0 ; i < 10 ; i++)
        {
   	       for (int j = 0 ; j < 10 ; j++)
         	   cout << setw(4) << k++;
   
      	   cout << endl;
        }
        system("PAUSE");
        return EXIT_SUCCESS;
    }
Example:
    #include <cstdlib>
    #include <iostream>
    #include <iomanip>

    using namespace std;

    int main(int argc, char *argv[])
    {
        int k;
        cout << "\n\nPrint 1 to 100 formatted by cout.width() :" << endl; 
        k = 1;
        for (int i = 0 ; i < 10 ; i++)
        {
            for (int j = 0 ; j < 10 ; j++)
            {
                cout.width(4);
                cout << k++;
            }
   
	           cout << endl;
        }
    
        system("PAUSE");
        return EXIT_SUCCESS;
    }
Example:
   int n=20;
   cout << dec << n << " in octal is " << oct << n << endl;
   cout << dec << n << " in decimal is " << dec << n << endl;
   cout << dec << n << " in hexadecimal is " << hex << n << endl;
    
Example:

    int n=20;
    cout << setbase(10) << n << " in octal is " << setbase(8) << n << endl;
    cout << setbase(10) << n << " in decimal is " << setbase(10) << n << endl;
    cout << setbase(10) << n << " in hexadecimal is " << setbase(16) << n << endl;
Example:

    #include <cstdlib>
    #include <iostream>
    #include <iomanip>
    #include <math.h>

    using namespace std;

    int main(int argc, char *argv[])
    {
       double root2 = sqrt(2.0);
       int places;
   
       cout << setiosflags( ios::fixed ) 
            << "Square root of 2 with precisions 0-9. \n"
            << "Precision set by the "
            << "precision member function:" << endl;
   
       for (places = 0 ; places <= 9 ; places++)
       {
           cout.precision( places );
           cout << root2 << endl;
       }
   
       cout << "\nPrecison set by the "
            << "setprecison manipulator:" << endl;
   
       for (places = 0 ; places <= 9 ; places++)
       	cout << setprecision(places) << root2 << endl;
   
       system("PAUSE");
       return EXIT_SUCCESS;
    }
    

 

練習:

  1. 試寫一程式印出 1 到 100 之間所有的整數 。
  2. 試寫一程式印出 1 到 100 之間所有的偶數。

 

Last update : 2006年2月17日