Question

Here is my code for my operator>> overload. It is supposed to take the numbers up to a semicolon and put them into a 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;
}

The problem I'm having is that when I run it, it gives me extra output. For example: when I type in "34;" as the input, the resulting bigint will be "3411". Can anyone tell me what I'm doing wrong?

Was it helpful?

Solution

You're not null-terminating your string temp. Add this:

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

Note the -1 will remove the semicolon that you probably don't need either. If you want to keep the semicolon there for whatever reason, change it to temp[i].

You should also add a check to your while loop to make sure you don't overflow your buffer size.

OTHER TIPS

You are guaranteeing a semicolon is in temp at the end. The semicolon is probably messing up whatever parsing bigint is doing with that string. Change the loop to test for the semicolon before inserting it into 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top