【问题标题】:Bigint operator >> overloadBigint 运算符 >> 重载
【发布时间】:2013-10-02 00:34:51
【问题描述】:

这是我的 operator>> 重载代码。它应该将数字带到分号并将它们放入 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”。谁能告诉我我做错了什么?

【问题讨论】:

  • SSCCE 会有所帮助。

标签: c++ operator-overloading bigint


【解决方案1】:

您没有以空值终止您的字符串temp。添加这个:

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

请注意,-1 将删除您可能也不需要的分号。如果您出于某种原因想要保留分号,请将其更改为 temp[i]

您还应该在 while 循环中添加一个检查,以确保不会溢出缓冲区大小。

【讨论】:

    【解决方案2】:

    您保证分号在末尾的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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      相关资源
      最近更新 更多