C++ Input Stream

               何謂串流呢?。當資料被輸入時,先放置到輸入串流(Input Stream),類似C語言的輸入緩衝區,並由get pointer來控制下一個
接收資料的位置,除此之外,並配合Error-Status Bits來控制輸入的狀態,其實Error-Status Bits的功能有點像是組合語言的旗標(Flags)
可在做輸入的動作時,檢測輸入是否正確或是產生錯誤。Error-Status Bits的定義可以在IOS.H中找到,如下(VC版本)
 
               enum io_state { goodbit = 0x00, eofbit = 0x01, failbit = 0x02, badbit = 0x04 };

 

先來看一個例子

        #include<iostream>
        using namespace std;
 
        int main()  {
 
                int num;
                char chr;
 
                cout << "Input one int:";
                cin >> num ;
                cout << "Input a character:";
                cin >> chr;
                cout << num << " " << chr <<endl;
                return 0;
        }


輸出(紅色代表輸入)
Input one int: A
Input a character:-858993460


說明

'A'會被放置到輸入串流(Input Stream)中,並以get pointer來控制下一個接收資料的位置  當執行第一個cin>>num;時,由於'A'的資料格式與num變數的型態不符合,使得輸入錯誤,而  建立旗標,使得所有cin>>operator不等待使用者輸入,而直接返回,除非明白予以清除,否則無法進行下一個輸入的動作。所以這一點與C語言的輸入緩衝區不同了。C語言可以在發生格式錯誤之後,仍然讀入資料,因此雖然scanf(...)不等待使用者輸入,但仍然從輸入緩衝區中處理輸入的動作。

 

如果輸入的資料與要求的型態不符合而產生輸入的錯誤時,如果從錯誤的狀況回復到正常的輸入狀態呢?請看一下的例子:

        // 轉載自C++ FAQ Lite
        // [15.3] How can I get std::cin to skip invalid input characters?
        // Use std::cin.clear
()  and std::cin.ignore()

        // (1) Clear the Error-Status

        // (2) Skip invalid input characters


        #include <iostream>

        #include <limits>

 

        int main()

        {

               int age = 0;

 

               while ((std::cout << "How old are you? ") && !(std::cin >> age)) {

                      std::cout << "That's not a number; ";

                      std::cin.clear();

                      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

               }

               std::cout << "You are " << age << " years old\n";

               return 0;

        }

 

Reference

1. C++ FAQ Lite

2. C++ Library Reference

 

Home

Written by James 2005/08/05

 

Hosted by www.Geocities.ws

1