2013-10-02 105 views
0

這是我的代碼爲我的運營商>>重載。它應該把數字分成一個分號並把它們放入一個bigint中。Bigint運營商>>超載

std::istream& operator>>(std::istream& is, bigint& bi) { 

    int i = 0; 
    char ch; 
    char temp[SIZE]; 

    // grabs the first character in the file 
    is >> ch; 
    temp[i] = ch; 
    ++i; 

    // while loop grabs the rest of the characters 
    // up to the semicolon 
    while(ch != ';') { 
     is >> ch; 
     temp[i] = ch; 
     ++i; 
    } 

    // temp is stored in the bigint ref 
    bi = bigint(temp); 

    return is; 
} 

我遇到的問題是,當我運行它時,它給了我額外的輸出。例如:當我輸入「34」時作爲輸入,所得到的bigint將是「3411」。誰能告訴我我做錯了什麼?

+0

[SSCCE](http://sscce.org)會有所幫助。 – chris

回答

0

你不是空終止您的字符串temp。補充一點:

temp[i - 1] = '\0'; 
bi = bigint(temp); 

-1將刪除你可能並不需要或者分號。如果您想因任何原因保留分號,請將其更改爲temp[i]

你還應該在你的while循環中添加一個檢查來確保你不會溢出你的緩衝區大小。

0

您在最後保證分號是temp。分號可能會搞亂bigint對該字符串的解析。改變回路將其插入temp之前測試的分號:

std::istream& operator>>(std::istream& is, bigint& bi) 
{ 
    char temp[SIZE] = {}; // zero out the array so the end is null terminated 
    char c; 

    for(int i = 0; i < SIZE-1 && is >> c && c != ';'; ++i) 
    { 
     temp[i] = c; 
    } 

    bi = bigint(temp); 
    return is; 
}