`
huozheleisi
  • 浏览: 1231152 次
文章分类
社区版块
存档分类
最新评论

C++ Stream I/O

 
阅读更多

C++ Stream I/O


  1. Stream Input/Output
  2. Stream I/O Applications
  3. Stream Output Concept
  4. Stream Input Concept
  5. Using C++ Objects
  6. Standard Output Stream
  7. Standard Output Stream, Cont.
  8. Formatted Output
  9. Standard Input Stream
  10. Standard Input Stream, Cont.
  11. Formatted Input
  12. Unformatted I/O Example
  13. What is EOF?
  14. Unformatted I/O Summary
  15. Formatted I/O
  16. Floating-point Precision
  17. Floating-point Manipulators
  18. Floating-point Example
  19. C++ String
  20. Line-based Input, std::getline
  21. String Stream
  22. Low-level I/O using String Stream
  23. Field Width
  24. Fill Character
  25. Field Alignment
  26. Alignment of Numeric Fields
  27. Scientific Notation
  28. Normalized Scientific Notation
  29. More Manipulator Examples
  30. Manipulators for Integer Data Types
  31. cin interpretation of 0 and 0x prefixes
  32. Manipulators for Floating-point Data Types
  33. C++ Standard Library Objects
  34. Stream Functionality

1. Stream Input/Output


  • Standard Outputcout,cerr

  • Standard Inputcin

  • Formatting

  • Error handling

  • File I/O (later)


2. Stream I/O Applications


  • network communication

  • encryption

  • data compression

  • persistent storage of objects

  • character-oriented input and output


3. Stream Output Concept


  • hardware monitor

  • 
        std::cout << "HELLO";
        std::cout << '\n';
        std::cout << 123;
    
    
  • Output stream buffer:

H E L L O \n 1 2 3 ... ...

4. Stream Input Concept


  • Input stream buffer:

4 5 6 \n 7 8 9 \n ... ...
  • hardware keyboard

  • 
        int one;
        int two;
        std::cin >> one;
        std::cin >> two;
    
    

5. Using C++ Objects


  • Objects are C++variablesofuser-defined types. They are declared as

    
        typename object_name;
    
    
  • For example, ifShape3Dis a user-defined type, then we could try

    
        Shape3D widget;               // create object named "widget"
    
        widget.display( parameters ); // call member function with parameters
    
        widget.reset( );              // call member function without parameters
    
    
  • Dot-notation is used to access functions built into objects.

  • Alternatively, some objects may allow use of arithmetic operators. For example,

    
        std::cout << widget;          // display widget on console output device
    
    


6. Standard Output Stream


  • 
        typename      object name
        ------------  -----------
        std::ostream  std::cout;  // cout is a predefined object
    
    
  • Usage example:

    
        #include <iostream> // C++ standard library header
    
        using std::cout;    // cout declared inside std namespace
    
        int main()
        {
            int x = 65;
            cout << x;      // display value of number 65
            cout.put( x );  // display character 'A'
            return 0;
        }
    
        /* This program prints:
        65A
        */
    
    


7. Standard Output Stream, Cont.


  • std::coutis a pre-defined object

  • We need to

    
        #include <iostream>
    
    

    to bringstd::coutinto our program

  • std::coutis attached to thestandard output device, which can be console display, file, or printer.

  • I/O redirection to file or printer is made easy:

    
    CMD> myprogram > myfile.txt
    
    

    The above command sends standard output tomyfile.txt


8. Formatted Output

  • C++ data types have OS- and hardware-specific internal representations...

    • ...If we display anumeric valueusingformatted output, its value is properlyconvertedto a corresponding sequence of characters.

    • ...If we display abool, we couldconvertits value to words"true"or"false".

  • Formatted Outputhandles value-to-text conversions for us:

    7 8 9 ; 0 . 5 ; t r u e

  • For example,

    
    #include <iomanip>
    #include <iostream>
    using std::cout;
    using std::boolalpha;
    
    int main( )
    {
         int i = 789;
         double d = 0.5;
         bool b = true;
    
         cout << i;
         cout << ';';
         cout << d;
         cout << ';';
         cout << boolalpha << b;
         return 0;
    }
    /* Program output:
    789;0.5;true
    */
    
    

9. Standard Input Stream


  • 
        typename      object name
        ------------  -----------
        std::istream  std::cin;    // cin is a predefined object
    
    
  • Usage:

    
        // formatted input of C++ variables
        int x;
        cin >> x;
    
        // unformatted input of single characters
        char x = cin.get( );
    
        // line-based input of text strings
        string text;
        getline( cin, text );
    
    


10. Standard Input Stream, Cont.


  • std::cinis a pre-defined object

  • We need to have

    
        #include <iostream>
    
    

    to bringstd::cininto our program

  • std::cinis attached to astandard input device

  • Example of I/O redirection from file or another device:

    
        CMD> myprogram < myfile.txt
    
    

    The above command gets standard input frommyfile.txt


11. Formatted Input


  • Formatted inputmeans

    1. reading expected type and format

    2. automatic whitespace processing

    
            #include <iostream>
    
            int main( )
            {
                int one;
                int two;
                std::cout << "Please enter two integers: ";
                std::cin >> one >> two;
                return 0;
            }
    
    


12. Unformatted I/O Example


  • Unformatted inputmeans

    1. reading individual characters

    2. discovering data type and format as you read

    
            #include <iostream>
    
            int main()
            {
                int onechar; // using int because char cannot represent EOF
    
                while ( ( onechar = std::cin.get() ) != EOF ) {
                    std::cout.put( onechar );
                }
    
                return 0;
            }
    
    


13. What is EOF?


  • AcronymEOFstands for condition known asend of file.

  • When reading from a file, the condition occurs naturally at the end of file.

  • To keep things consistent, the condition is also triggered when user enters

        CTRL+Z (on Windows machine)
    
        CTRL+D (on Unix machine)
    

    on the keyboard.

  • EOFis asymbolthat becomes defined after

    
        #include <iostream>
    
    


14. Unformatted I/O Summary

  • Unformattedis typically viewed as

    • low-level I/O

    • highest efficiency

    • individual character processing

  • Input normally finishes atend-of-filemarker,EOF

  • Input proceeds regardless of multiple lines of text

  • Input has no automatic whitespace recognition

  • 
    // Unformatted output
    std::ostream std::cout;     // predefined
    
    cout.put( c );              // single byte
    
    cout.write( array, count ); // array of bytes
    
    
    
    // Unformatted input
    std::istream std::cin;      // predefined
    
    c = cin.get( );             // single byte
    
    cin.read( array, count );   // array of bytes
    
    

15. Formatted I/O


  • Floating-point values by default use fixed-point notation:

    
        #include <iostream>
        int main()
        {
          const double PI = 3.1415926;
          std::cout << PI << '\n';
          return 0;
        }
        /*
        Output: 3.14159
        */
    
    


16. Floating-point Precision

  • Floating-point values are printed withexact fraction part,as specified by theprecision.

  • Indefault notationformat, the precision specifiesmax number of meaningful digitsto display bothbefore and afterthe decimal point.

  • Thedefault precisionis 6 digits.

  • This means that the value is rounded to the best approximation while using 6 digits.

  • If necessary, the default format may change to scientific notation to preserve most accurate representation.

  • Precision can be changed by callingprecision()member function of the stream to improve data accuracy:

    
    #include <iostream>
    void main()
    {
      const double PI = 3.1415926;
      std::cout.precision( 7 );
      std::cout << PI << '\n';
    }
    /*
    Output: 3.141593
    */
    
    

17. Floating-point Manipulators


  • There are three possible ways to format floating point values:

    
        cout << value // default
    
        cout << fixed << value
    
        cout << scientific << value
    
    
  • Infixedandscientificnotations precision specifies exactlyhow many digits to displayafter the decimal point, even if they are trailing decimal zeros.


18. Floating-point Example


  • 
        #include <iostream>
        using namespace std;
        int main()
        {
            const double PI = 3.1415926;
            cout.precision( 7 );
            cout << fixed << "fixed format: " << PI << '\n';
            cout << scientific << "scientific format: " << PI << '\n';
            // back to default format:
            cout.unsetf( ios_base::fixed );
            cout.unsetf( ios_base::scientific );
            cout << "default format: " << PI << '\n';
            return 0;
        }
        /*
        Output:
        fixed format: 3.1415926
        scientific format: 3.1415926e+000
        default format: 3.141593
        */
    
    


19. C++ String

  • std::stringstores and manipulates text data

  • Add

    
        #include <string>
    
    

    to bringstd::stringtype into our program

  • 
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        int qty;
        string units;
    
        // Formatted input of text:
        cout << "Qty and units: ";
        cin >> qty;
        cin >> units;
    
        cout << "You entered: ";
        cout << qty;
        cout << ' ';
        cout << units;
        cout << '\n';
        return 0;
    }
    
    

20. Line-based Input, std::getline


  • 
        #include <iostream>
        #include <string>
        using namespace std;
    
        int main()
        {
            string text_line;
    
            // Line-based input of text:
            cout << "Type something: ";
            getline( cin, text_line );
    
            cout << "You typed: ";
            cout << text_line;
            cout << '\n';
    
            return 0;
        }
    
    


21. String Stream


  • 
        #include <cassert>
        #include <string> 
        #include <sstream> 
        int main()
        {
            const double PI = 3.1415926;
            double value;
            std::stringstream  buffer;  // text buffer
            buffer.precision( 8 );      // increase default precision (*)
            buffer << PI;               // formatted output  
            buffer >> value;            // formatted input
            assert( PI == value );
            std::string text; 
            text = buffer.str( );  // returns std::string  
            buffer.str( "" );      // clear buffer  
            return 0;
        }
    
    

    (*) try commenting out precision change and see what happens


22. Low-level I/O using String Stream


  • 
        #include <cassert>
        #include <iostream>
        #include <sstream>
        using namespace std;
        int main()
        {
            stringstream buffer;
            int onechar; // because char cannot represent EOF
            cout << "Enter some text: ";
            while ( ( onechar = cin.get() ) != EOF ) {
                if ( onechar == '\n' ) {
                    break; // exit loop at the end of the line
    
                } else if ( isalpha( onechar ) ) {
                    buffer << "alpha: " << char( onechar ) << '\t' << onechar <<'\n';
    
                } else if ( isdigit( onechar ) ) {
                    buffer << "digit: " << char( onechar ) << '\t' << onechar <<'\n';
    
                } else {
                    buffer << "other: " << char( onechar ) << '\t' << onechar <<'\n';
                }
            }
            cout << buffer.str() << '\n'; // str() returns string
            return 0;
        }
    
    


23. Field Width


  • Manipulatorstd::setw( n )determines minimum output widthn.

  • Requires header

    
        #include <iomanip>
    
    
  • If output is shorter than thefield widthn, the output is padded withfill characters.

    
        #include <iostream>
        #include <iomanip>
        using namespace std;
        int main () {
            cout << setw( 40 ) << "Hello";
            return 0;
        }
        /*
        Output:
                                         Hello
        */
    
    


24. Fill Character


  • Fill charactercan be changed bysetfillmanipulator:

    
        #include <iostream>
        #include <iomanip>
        using namespace std;
        int main () {
            cout << setfill( '?' ) << setw( 40 ) << "Hello";
            return 0;
        }
        /*
        Output:
        ???????????????????????????????????Hello
        */
    
    


25. Field Alignment


  • leftappends fill characters at the end.

  • rightinserts fill characters at the beginning.

    
        #include <iostream>
        #include <iomanip>
        using namespace std;
        int main () {
            cout << left << setfill( '?' ) << setw( 40 ) << "Hello";
            return 0;
        }
        /*
        Output:
        Hello???????????????????????????????????
        */
    
    


26. Alignment of Numeric Fields


  • Adjusting numeric fields:

    
        #include <iostream>
        #include <iomanip>
        using namespace std;
        int main() {
          int x = -1234;
          cout << setw( 10 ) << internal << x << '\n';
          cout << setw( 10 ) << left     << x << '\n';
          cout << setw( 10 ) << right    << x << '\n';
          return 0;
        }
        /*
        Output:
        -     1234
        -1234
           -1234
        */
    
    


27. Scientific Notation


  • Scientific notation(exponential notation) adjusts specifieddecimal pointto the left or to the right according to the specified value of exponente.

  • Thee-suffix representstimes ten raised to the power. For example,

            1e-2 ==   0.01 == 1×10-2
    
            1e-1 ==   0.10 == 1×10-1
    
            1e-0 ==   1.00 == 1×100
    
            1e+0 ==   1.00 == 1×100
    
            1e+1 ==  10.00 == 1×101
    
            1e+2 == 100.00 == 1×102


28. Normalized Scientific Notation


  • Normalized scientific notationexpects absolute partA(*)of the numberA×10bto be in the range

    • 1 <=A< 10

  • Try the following program to convert numbers from scientific notation to ordinary decimal notation:

    
        #include <iostream>
        #include <iomanip>
        using namespace std;
    
        int main() {
            for (;;) {
                double dbl;
                cin >> dbl;
                cout << setw( 14 ) << showpoint << dbl << '\n';
            }
            return 0;
        }
    
    
  • ________________

    (*) the absolute partAis also known asmantissa.


29. More Manipulator Examples


  • 
    #include <iostream>
    #include <iomanip>
    using namespace std;
    int main() {
    /*         5600 */ cout << setw( 14 )               << 56e2 << '\n';
    /*      5600.00 */ cout << setw( 14 ) << showpoint  << 56e+2 << '\n';
    /*2.345678e+002 */ cout << setw( 14 ) << scientific << 234.5678 << '\n';
    /*          255 */ cout << setw( 14 )               << 255 << '\n';
    /*           ff */ cout << setw( 14 ) << hex        << 255 << '\n'; 
    /*          377 */ cout << setw( 14 ) << oct        << 255 << '\n';
    /*            1 */ cout << setw( 14 )               << true << '\n';
    /*         true */ cout << setw( 14 ) << boolalpha  << true << '\n';
    /*  1234.567890 */ cout << setw( 14 ) << fixed      << 1234.56789 << '\n';
    /*     1234.568 */ cout << setw( 14 ) << fixed << setprecision(3) << 1234.56789 << '\n';
        return 0;
    }
    /*
    Output:
              5600
           5600.00
     2.345678e+002
               255
                ff
               377
                 1
              true
       1234.567890
          1234.568
    */
    
    


30. Manipulators for Integer Data Types


  • The following areinteger output manipulators:

    • boolalpha: use symbolic representation oftrueandfalsewhen inserting or extractingboolvalues. By default,boolvalues inserted and extracted as numeric values1and0.

    • dec: insert or extract integer values in decimal (base 10) format.

    • hex: insert or extract integer values in hexadecimal (base 16) format, such as "0xFF" or simply "FF".

    • oct: insert or extract integer values in octal format, e.g. "077"

    • showbase: insert a prefix that reveals the base of an integer value.

    • noshowbase: reverse back to baseless integer output format.

  • Note: the above manipulators aresticky: they persist until another manipulator is applied.

  • The data type manipulators can be applied to bothinputandoutputstreams.


31. cin interpretation of 0 and 0x prefixes


  • 
        cin.unsetf( ios::dec ); // Interpret 0 and 0x as hexadecimal and octal prefixes
        cin.unsetf( ios::oct ); // Ignore octal prefix, interpret 077 as decimal 77
    
        cin.unsetf( ios::dec );
        cin.setf( ios::oct );   // All integers now expected to be octal base
    
        cin.unsetf( ios::dec );
        cin.setf( ios::hex );   // All integers now expected to be base-16:
    
    
  • Sample programcin_setf.cpp(download) illustrates integer base/prefix manipulation and rudimentary format-related error recovery.

  • See also<noindex><a href="http://www.cplusplus.com/reference/iostream/ios_base/setf.html" target="_blank"><tt>cin.setf()</tt></a></noindex>and<noindex><a href="http://www.cplusplus.com/reference/iostream/ios_base/unsetf.html" target="_blank"><tt>cin.unsetf()</tt></a></noindex>documentation.


32. Manipulators for Floating-point Data Types


  • showpoint: insert a decimal point unconditionally in a generated floating-point field.

  • fixed: insert floating-point values in fixed-point format. For example,

    • default format for1234.56789is1234.57,

    • fixed makes it1234.56789.

  • scientific: insert floating-point values in scientific format with an exponent field. For example,

    • default format for1234.56789is1234.567,

    • scientificmakes it1.234568e+03.

  • Note: the above manipulators aresticky: they persist until another manipulator is applied.


33. C++ Standard Library Objects


  • 
        typename           object name
        ------------       -----------
        std::ostream       std::cout; // predefined object
        std::istream       std::cin;  // predefined object
        std::string        text;      // text data
        std::stringstream  buffer;    // text buffer
    
    


34. Stream Functionality


分享到:
评论

相关推荐

    C++中I/O模型之select模型实例

    本文实例讲述了C++中I/O模型的select模型用法。分享给大家供大家参考。具体实现方法如下: 代码如下:void main()  {   CInitSock initSock;   USHORT nPort = 9999; //监听的端口   SOCKET sListen = ::...

    C++ For Dummies

    and destructorsDiscover how the concept of inheritance is the key to effective C++ programmingWork with assignment operators, stream I/O, and other more advanced concepts, once you’ve grasped the ...

    C++ Standard Library Quick Reference

    • What functionality the library provides for file and stream-based I/O • What smart pointers are and how to use them to prevent memory leaks • How to write safe and efficient multi-threaded code ...

    C++ 大学自学教程 C++ 大学教程 第7版 2

    29,文件I/O流 第四部分 标准模板库 30,STL简介 31,STL序列容器 32,结合容器 33,通用算法 34,迭代器 第五部分 高级问题 35,异常处理 36,名字空间 37,C++类型强制转换 38,运行时类型信息 39,区域表示 40,...

    .NET Programming with Visual C++: Tutorial, Reference, and Immediate Solutions

    NET File and Stream I/O CHAPTER 8: ADO. NET: DataSets, Data Tables, and XML CHAPTER 9: ADO. NET: OLE DB and SQL Server Data Providers CHAPTER 10: Creating ASP. NET Web Services CHAPTER 11: Consuming ...

    c++大学自学教程 c++大学教程 第七版1

    29,文件I/O流 第四部分 标准模板库 30,STL简介 31,STL序列容器 32,结合容器 33,通用算法 34,迭代器 第五部分 高级问题 35,异常处理 36,名字空间 37,C++类型强制转换 38,运行时类型信息 39,区域表示 40,...

    c++大学自学教程 c++大学教程 第七版 4

    29,文件I/O流 第四部分 标准模板库 30,STL简介 31,STL序列容器 32,结合容器 33,通用算法 34,迭代器 第五部分 高级问题 35,异常处理 36,名字空间 37,C++类型强制转换 38,运行时类型信息 39,区域表示 40,...

    C++中的文件操作_Vc_

    C++达人编写的C++文件操作编程教程 pdf,不涉及其它方面的C++教程,主要是讲解C++中的I/O流、Stream类以及一些重要的运算符

    LeetCode最全代码

    I'll keep updating for full summary and better solutions. Stay tuned for updates. (Notes: "馃摉" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the ...

    c++大学自学教程 c++大学教程 第七版 3

    29,文件I/O流 第四部分 标准模板库 30,STL简介 31,STL序列容器 32,结合容器 33,通用算法 34,迭代器 第五部分 高级问题 35,异常处理 36,名字空间 37,C++类型强制转换 38,运行时类型信息 39,区域表示 40,...

    C++文件操作编程教程

    这是C++达人编写的C++文件操作编程教程 pdf,不涉及其它方面的C++教程,主要是讲解C++中的I/O流、Stream类以及一些重要的运算符,包括了文件打开、修改文件、删除、追加文件内容、读写文件、C++中的文件输入/输出、...

    C++ Standard Library: A Tutorial and Reference

    Input/Output Using Stream Classes&lt;br/&gt;&lt;br/&gt;13.1 Common Background of I/O Streams&lt;br/&gt;&lt;br/&gt;13.2 Fundamental Stream Classes and Objects&lt;br/&gt;&lt;br/&gt;13.3 Standard Stream Operators &lt;&lt; and &gt;&gt;&lt;br/&gt;&lt;br/&gt;13.4 ...

    A JSON parser in C++

    Perhaps because web service clients are usually written in dynamic languages these days, none of the existing C++ JSON parsers fitted my needs very well, so I wrote one that I used in another project....

    C++实验报告

    I/O Stream 应用、文件操作 写一个程序来计算一门课的成绩(以满分 100 计)。

    ofstream和ifstream详细用法 .doc

    ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间;...在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:

    C++简述小程序

    代替该命令行。文件iostream的作用是向程序提供输入或输出时所需要的一些信息。iostream是i-o-stream 3个词的组合,从它的形式就可以知道它代表“输入输出流”的意思,由于这类文件都放在程序单元的开头,所以称为...

    Apress.Cplusplus17.Standard.Library.Quick.Reference.1484249224.pdf

    Work with file and stream-based I/O Prevent memory leaks with smart pointers Write safe and efficient multi-threaded code using the threading libraries Who This Book Is For All C++ programmers, ...

    C++ ofstream与ifstream详细用法

    在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符: 1、插入器(&lt;&lt;) 向流输出数据。比如说系统有一个默认的标准输出流(cout),一般...

Global site tag (gtag.js) - Google Analytics