I just implemented code to add two ints together as strings and I'm sure my method is inferior. I've looked up other methods too but I'd appreciate criticisms specific to my code. I really want to make sure I don't develop bad habits in C++ and I think leveraging the knowledge of brighter individuals than myself on this site will help with that :). Am I relying too much on iterators btw?
Anyhow, the code is below and be as harsh as you want. Thanks!
//This program intends to read very large integers from a text file
//the format is two integers per line. It will then add them together and output
//the sums one each line
//first, succesfully read from the text file and store into two vectors
//each digit being an element
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string line,s1,s2;
vector<string> vec1, vec2; //string 1 and string 2 store each of the 2 numbers per line as individual digits
vector<string> final; //create vector of strings that holds the sum of each pair of strings per line
ifstream myfile("bignum.txt"); //this opens the file bignum.txt
if (myfile.is_open())
{
int count=0; //count lines
while (!myfile.eof())
{
getline(myfile,line);
bool flag=true; //bool to see if integer 2 should be stored now
for (int i=0; i<line.length(); i++)
{
if (line[i]==' ')
flag=false;
else
{
if (flag)
s1+=line[i];
else
s2+=line[i];
}
//by the end of this loop we have two strings representing each of the numbers
}
//will now append 0's to the front of the smaller string in order to make the strings the same length
if (s1.length()<s2.length())
s1=string(s2.length()-s1.length(),'0')+s1;
else
s2=string(s1.length()-s2.length(),'0')+s2;
//create a variable that acts as the surplus/carry for each single-digit addition
int carry=0;
//create iterators allowing for iteration over a vector
string::reverse_iterator it1 = s1.rbegin(),it2=s2.rbegin();
string sum_string="";
for (; it1!=s1.rend(); it1++, it2++)
{
//convert chars to ints
int k1=*it1-'0';
int k2=*it2-'0';
//intermediate sum
int sum_inter=k1+k2+carry;
carry=0;
sum_string.insert(0,to_string(sum_inter%10));
carry+=int((sum_inter-sum_inter%10)/10);
};
//insert the last carry into the highest digit position
sum_string.insert(0,to_string(carry));
//go through sum_string and omit leading 0's
bool lead_zero=true;
string::iterator leadit=sum_string.begin();
while(lead_zero)
{
if (int(*leadit-'0')==0)
sum_string.erase(0,1);
else
lead_zero=false;
}
final.push_back(sum_string);
//clear strings 1 and 2 for reuse
s1.clear();
s2.clear();
}
vector<string>::iterator i1=final.begin();
int count3=0;
for (; i1!=final.end(); i1++)
{
count3++;
cout<<"The sum of the numbers on line "<<count3<<" is "<<*i1<<"\n";
}
}
else cout <<"file could not be opened";
return 0;
}