Issue with overloaded output operator (previous post didn't submit)

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
The reason is that size_t is unsigned, hence it will never be < 0.

1
2
3
4
5
6
7
8
9
std::ostream& operator<<(std::ostream &out, const BigInt &bigInt)
{
	const std::size_t size = bigInt.m_digits.size();
	for (std::size_t i = 0; i < size; ++i)
	{
		out << (bigInt.m_digits)[size - 1 - i];
	}
	return out;
}
Last edited on
Your previous post did submit, I can see it :p
btw on line 24, variable i is being used without being initialized.
Oh, well, that's stupid. Thanks alot for pointing out these mistakes!
Since you are converting the integer to a string, you end up putting each of the characters of the string into the vector of ints. This is legal, but the values in the vector will be the ASCII values associated with the characters representing the digits. When you print them out, you will get what appears to be garbage.
Topic archived. No new replies allowed.