Issue with overloaded output operator
Jul 5, 2017 at 1:39pm UTC
Hi everyone!
I'm writing a BigInt class (now with a vector containing the digits, instead of a string), and my program crashes when I try to use the overloaded output operator. First it outputs alot of garbage numbers, and then the program crashes. Can anyone help me with this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
//BigInt.h
#ifndef BIGINT_H
#define BIGINT_H
#include <vector>
#include <string>
#include <iostream>
class BigInt
{
private :
std::vector<int > m_digits;
public :
BigInt(int digits);
friend std::ostream& operator <<(std::ostream &out, const BigInt &bigInt);
};
#endif
//BigInt.cpp
#include "BigInt.h"
BigInt::BigInt(int digits)
{
//store the number in reverse order, this makes it easier to calculate the 'real' value of every digit
std::string digits_s = std::to_string(digits);
for (std::size_t i; i < digits_s.length(); ++i)
m_digits.push_back(digits_s[i]);
}
/*OPERATORS*/
/*Input/Output operators*/
std::ostream& operator <<(std::ostream &out, const BigInt &bigInt)
{
for (std::size_t i = (bigInt.m_digits).size()-1; i >= 0; --i)
{
out << (bigInt.m_digits)[i];
}
return out;
}
//main source file for testing
#include "BigInt.h"
#include <iostream>
int main()
{
BigInt a(123);
std::cout << a;
return 0;
}
Thanks
Jul 5, 2017 at 4:23pm UTC
There is no way for the condition i >= 0 to be false because std::size_t is an unsigned type which means it cannot store negative values.
Another problem is that you've forgot to initialize i in the constructor.
Topic archived. No new replies allowed.