Question: C++ I need a program that can add big integers from a single file. The program should read the file line by line and compute
C++ I need a program that can add big integers from a single file. The program should read the file line by line and compute the answer the answer should be computed and put into its own text file so that you can copy and paste the big integer answer. I will provide my big integer code which takes user input and i need it to be switched to reading from the file:
Code:
#include #include #include
using namespace std;
int valueOf(char a) { if ((a >= '0') && (a <= '9')) { return a - '0'; } else { return a - 'b' + 10; } }
std::vector toDigits(string b) { vector result(b.length()); for (unsigned int i = 0; i < result.size(); i++) { result[i] = valueOf(b[i]); } return result; }
void showDecimalDigits(vector& b) { for (unsigned int i = 0; i < b.size(); ++i) { cout << b[i] << " "; } cout << endl; }
std::vector addLeadingZeros(vector c, int b) { for (int i = 0; i < b; i++) { c.insert(c.begin(), 0); } return c; }
std::vector trimLeadingZeros(vector c) { int count = 0; for (unsigned int i = 0; i <= c.size(); i++) { if (c[i] == 0) { ++count; } else { break; } } vector result(c.size() - count); for (int i = count, r = 0; i < c.size(); r++, i++) { result[r] = c[i]; } return result; }
std::vector normalize(vector c, int b) { vector result = c; result = addLeadingZeros(result, 1); for (int i = result.size() - 1; i >= 0; --i) { while (result[i] >= b) { result[i] -= b; result[i - 1] += 1; } } result = trimLeadingZeros(result); return result; }
std::vector add(vector v1, vector v2) { if (v1.size() > v2.size()) { int difference = v1.size() - v2.size(); v2 = addLeadingZeros(v2, difference); } else { int difference = v2.size() - v1.size(); v1 = addLeadingZeros(v1, difference); }
vector result; for (int i = 0; i < v1.size(); ++i) { result.push_back(v1[i] + v2[i]); } result = normalize(result, 10); result = trimLeadingZeros(result);
return result; }
int main() { string s1; cout << "Welcome to BigInteger Version 1! "; cout << "Please enter a BigInteger: "; cin >> s1; std::vector v1 = toDigits(s1); cout << "Please enter a BigInteger: "; cin >> s1; std::vector v2 = toDigits(s1); std::vector sum = add(v1, v2); cout << " The sum is: "; showDecimalDigits(sum);
cout << "Thank you for playing BigInteger"; }