Reputation: 59
I have been trying to read two numbers as string, convert them into int vectors, then add them for my lab at school. I have run my code to find this error:
Debug Assertion Failed!
Program: C:\windows\SYSTEM32\MSVCP140D.dll File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\xstring Line: 1681
Expression: vector subscript out of range
For more information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
I have tried retrying but it opens up another dialog box that says the debug reached a breakpoint, at which point I could not continue debugging. Here is my code for those of you interested (Microsoft Visual Studio Compiler):
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void input(string &largeString1, string &largeString2);
void convert(string largeString1, string largeString2, vector<int> &largeInt1, vector<int> &largeInt2);
int asciiToInt(char ch);
void add(vector<int> largeInt1, vector<int> largeInt2, vector<int> &finalInt);
void output(const vector<int> finalInt);
int main()
{
string largeString1;
string largeString2;
vector<int> largeInt1(12, 0);
vector<int> largeInt2(12, 0);
vector<int> finalInt(13, 0);
for (int i = 0; i < 4; i++)
{
input(largeString1, largeString2);
convert(largeString1, largeString2, largeInt1, largeInt2);
add(largeInt1, largeInt2, finalInt);
output(finalInt);
}
system("pause");
return 0;
}
void input(string &largeString1, string &largeString2)
{
cout << "Input:" << endl << endl;
cin >> largeString1;
cin >> largeString2;
}
void convert(string largeString1, string largeString2, vector<int> &largeInt1, vector<int> &largeInt2)
{
int size1 = size(largeString1);
int size2 = size(largeString2);
for (int i = 0; i < 12; i++)
{
int dynamicsize1 = size1 - i;
largeInt1[11 - i] = asciiToInt(largeString1[dynamicsize1 ]);
}
for (int j = 0; j < 12; j++)
{
int dynamicsize2 = size2 - j;
largeInt2[11 - j] = asciiToInt(largeString2[dynamicsize2 ]);
}
}
int asciiToInt(char ch)
{
return (ch - '0');
}
void add(vector<int> largeInt1, vector<int> largeInt2, vector<int> &finalInt)
{
for (int i = 0; i < 13; i++)
{
finalInt[12 - i] = largeInt1[11 - i] + largeInt2[11 - i];
}
}
void output(const vector<int> finalInt)
{
cout << endl << "Output:" << endl << endl << "The sum is: ";
for (int i = 0; i < 13; i++)
{
cout << finalInt[i];
}
}
Upvotes: 0
Views: 192
Reputation: 6875
I believe here is the bug you are looking for:
void add(vector<int> largeInt1, vector<int> largeInt2, vector<int> &finalInt)
{
for (int i = 0; i < 13; i++)
{
finalInt[12 - i] = largeInt1[11 - i] + largeInt2[11 - i];
}
}
Note that largeInt1
and largeInt2
are of size 12. However when i
reaches 12 you get -1 index
finalInt[0] = largeInt1[-1] + largeInt2[-1];
Upvotes: 1