my assignment is to do the following:
Generate some rows of numeric digits. Use the random number generator.
Ask the user for the number of rows and columns of digits. 2x4 would look like this...
0655
6476
Treat each row of digits as a single number. Show the sum using addition. Example:
0655
6476
7131 < sum of 0655 and 6476
Now I've gotten it to mostly work with the code below.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
int x;
int y;
int total = 0;
int sum[100];
int num;
string val= "";
srand((unsigned)time(NULL));
cout << "\nHow many rows?\n" << endl;
cin >> x;
cout << "\nHow many columns?\n" << endl;
cin >> y;
int rows = x;
int columns = y;
for (int i=0; i<rows; i++) {
cout << " ";
for (int j = 0; j < columns; j++) {
int r = rand() % 10;
sum[j]= r;
if (j == columns - 1){
for (int k = 0; k <= j; k++ ) {
val = val + to_string(sum[k]);
}
num = stoi(val);
total += num;
val = "";
}
cout << r;
}
cout << endl;
}
cout << " "<< total << endl;
cout << endl;
cout << "program complete.\n" << endl;
return 0;
}
However, whenever the y value from user input is 10 or higher I get the error:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
No errors from any x value from user input as far as I can tell.
Is this just a bad way of doing this? Should I scrap the code and try a different method?