2011-10-20 116 views
0

儘管我對C++相當陌生,但我還沒有完全熟悉這個術語,所以我對提前模糊的聲音表示歉意!重載操作員幫助?

我的問題是我很努力地看到爲什麼我的while循環似乎停止我的重載操作函數中的其他方法;

#include "sample.h" 

#include <iostream> 
#include <vector> 
#include <cstdlib> 

using namespace std; 

sample::sample(vector<double> doubles){} 

sample::sample() {} 

ostream& operator<< (ostream &out, sample &sample) 
{ 
    out << "<" << sample.n << ":"; 
    return out; 
} 

istream& operator>> (istream &in, sample &sample) 
{ 
    char firstChar; 
    in >> firstChar; 

    if(firstChar != '<'){ 
     cout << "You've not entered the data in a valid format,please try again!1 \n"; 
     exit(1); 
    } 

    int n; 
    in >> n; 
    sample.n = n; 

    char nextChar; 
    in >> nextChar; 
    if(nextChar != ':'){ 
     cout << "You've not entered the data in a valid format,please try again!2 \n"; 
     exit(1); 
    } 

    vector<double> doubles; 
    double number; 
    while (in >> number){ 
     doubles.push_back(number); 
     cout << in << " " << number; 
    } 
    in >> lastChar; 

    return in; 
} 

int main(void) 
{ 
    sample s; 
    while (cin >> s){ 
     cout << s << "\n"; 
    } 

    if (cin.bad()) 
     cerr << "\nBad input\n\n"; 

    return 0; 
} 

我的輸入是類似的東西;

< 6:10.3 50 69.9>

我試圖讓之後的所有雙打「:」爲載體,如果他們整數我可以做,但一旦「」進入它似乎停止。

如果我只是把整數,它似乎也停止while(in >> number)已經完成查找所有的數字後,這很好,但在我的主要功能cout<<命令似乎並不工作!

我哪裏出錯了?

回答

1

您必須遵守的標準流成語:每一個流隱式轉換爲一個布爾值(或空指針),以允許像檢查if (in >> n)查看操作是否成功。所以首先你必須確保你的操作符符合這個要求(通過確保提取成功的流是「好的」)。其次,當你編寫一個像while (in >> x) { /*...*/ }這樣的循環時,循環終止後,你已經知道你的流不再好。因此,在返回之前,您必須先致電clear()

也許是這樣的:

std::istream& operator>> (std::istream &in, sample &sample) 
{ 
    char c; 
    int n; 
    double d; 
    std::vector<double> vd; 

    if (!(in >> c)) { return in; }        // input error 
    if (c != '>') { in.setstate(std::ios::bad); return in; } // format error 

    if (!(in >> n)) { return in; }        // input error 

    if (!(in >> c)) { return in; }        // input error 
    if (c != ':') { in.setstate(std::ios::bad); return in; } // format error 

    while (in >> d) 
    { 
    vd.push_back(d); 
    } 

    in.clear(); 

    if (!(in >> c)) { return in; }        // input error 
    if (c != '>') { in.setstate(std::ios::bad); return in; } // format error 

    state.n = n; 
    state.data.swap(vd); 

    return in; 
} 

注意,如果整個輸入操作成功,我們只修改sample對象。

+0

感謝Kerrek,我有一個更好的理解,但混淆清楚的方法實際上做什麼?!當你調用一個清除函數時,我試圖從數據的數字部分到最後一個字符? – r0bb077

+0

它根本不「走」; 'clear'只是重置錯誤標誌,以便完全執行下一個提取操作(不會在錯誤的流上執行提取操作)。 –

+0

真棒,應該真的假設!再次感謝您的幫助! – r0bb077

0
cout << in << " " << number; 

你可能是指

cout << " " << number; 

什麼

+0

對不起,作爲一個絕望的代碼來看看它輸入向量中的數字時,我應該從代碼中刪除,當我把它粘貼在這裏! – r0bb077