Bigint运算符>>过载

Bigint operator >> overload

本文关键字:gt 过载 运算符 Bigint      更新时间:2023-10-16

这是我的运算符的代码>>重载。它应该将数字上升到分号并将它们放入一个 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"。谁能告诉我我做错了什么?

您不会以 null 终止字符串temp .添加这个:

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

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

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

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