Answer the question
In order to leave comments, you need to log in
Why bad_alloc error?
A simple "a+b from a file on one line" task. On startup, bad_alloc occurs. Tell me, what's wrong?
#include <fstream>
#include <vector>
void do_sum(std::vector<int>& v_max, std::vector<int>& v_min) //сложение
{
int i_max=v_max.size(), i_min=v_min.size();
int temp=0;
do{
i_min--; i_max--;
temp=v_max[i_max]+v_min[i_min];
v_max[i_max]=temp%10;
i_max!=0?(v_max[i_max-1]+=temp/10):v_max[i_max]=temp;
}while(i_min>0);
}
void do_read(std::vector<int>& v1,std::vector<int>& v2, std::string filename) // считывание
{
std::ifstream input_file(filename);
char c='0';
bool flag=true;
while(flag){
input_file>>c;
if (c!=' ') v1.push_back(static_cast<int>(c-'0')); else flag=false;
}
while(input_file.get(c))
{
v2.push_back(static_cast<int>(c-'0'));
}
input_file.close();
}
void do_write(std::vector<int>& v, std::string filename) // запись
{
int size=v.size();
std::ofstream output_file(filename);
for(int i=0; i<size; i++)
output_file<<v[i];
output_file.close();
}
int main()
{
std::string filenameIn="INPUT.txt", filenameOut="OUTPUT.txt";
std::vector<int> v1,v2;
do_read(v1,v2,filenameIn);
if (v1.size()>=v2.size())
{
do_sum(v1,v2);
do_write(v1,filenameOut);
}
else
{
do_sum(v2,v1);
do_write(v2,filenameOut);
};
return 0;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question