2013-10-02 109 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; 
}