In: Computer Science
Why does my code print nothing in cout? I think my class functions are incorrect but I don't see why.
bigint.h:
#include <string>
#include <vector>
class BigInt {
private:
int m_Input, m_Temp;
std::string m_String = "";
std::vector<int> m_BigInt;
public:
BigInt(std::string s) // convert string to
BigInt
{
m_Input = std::stoi(s);
while (m_Input != 0)
{
m_Temp = m_Input
% 10;
m_BigInt.push_back(m_Temp);
m_Input %=
10;
}
}
std::string to_string() // get string
representation
{
for (auto digit : m_BigInt)
{
m_String +=
std::to_string(digit);
}
return m_String;
}
void add(BigInt b) // add another BigInt to this
one
{
for (int digit = 0; digit !=
b.getVect().size(); digit++)
{
this->getVect()[digit] += b.getVect()[digit];
}
}
std::vector<int> getVect() // get BigInt
vector
{
return m_BigInt;
}
};
test1.cpp:
#include "bigint.h"
#include
using namespace std;
int main() {
BigInt a("13");
BigInt b("42");
b.add(a); // increase b by a
cout << b.to_string() << endl; // prints
55
b.add(a); // increase b by a
cout << b.to_string() << endl; // prints
68
}
In case of any query do comment. Please rate answer as well. Thanks
Note: there were few problems in the program, but still you require to change add function to handle carry in addition. Other thing was when you were trying to find a digit to put it in bigInt vector, it was running infinitely as you were not dividing the digit by 10 to get next digit. This is corrected and also when you convert vector to string you have to use reverse iterator because you are pushing digits to the back.
Code:
#include <string>
#include <vector>
class BigInt {
private:
int m_Input, m_Temp;
std::string m_String = "";
std::vector<int> m_BigInt;
public:
BigInt(std::string s) // convert string to BigInt
{
m_Input = std::stoi(s);
while (m_Input != 0)
{
m_Temp = m_Input % 10;
m_BigInt.push_back(m_Temp);
m_Input /= 10;
}
}
std::string to_string() // get string representation
{
//clear the m_String every time when your print
m_String ="";
//you need to reverse iterate the vector
for (auto it = m_BigInt.rbegin(); it != m_BigInt.rend(); it++)
{
m_String += std::to_string(*it);
}
return m_String;
}
void add(BigInt b) // add another BigInt to this one
{
for (int digit = 0; digit != b.getVect().size(); digit++)
{
m_BigInt[digit] += b.getVect()[digit];
}
}
std::vector<int> getVect() // get BigInt vector
{
return m_BigInt;
}
};
=============difference in code=======
output: