I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i need help creating 7 functions to break this code into. By using pass by reference. i can't figure out how to pass the multidimensional arrays between functions.
#include <fstream>
#include <string>
#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int courseSize = 3;
const int examSize = 6;
int n=0;
int strLength =0;
double scoreTotal =0;
char lettergrade;
string header, name, address, phone, social, course, studentID;
const int letterGrade_A = 90;
const int letterGrade_B = 80;
const int letterGrade_C = 70;
const int letterGrade_D = 60;
int age, yearsAtTXST, numstudents;
double testscore;
double numGrade = 0;
const int minStrLength = 1;
const int maxStrLength = 100;
const int minint = 1;
const int maxint = 100;
const int minCourse = 1;
const int maxCourse = 3;
const int minTest = 1;
const int maxTest = 5;
const double test1 = 0.10;
const double test2 = 0.15;
const double test3 =0.15;
const double test4 = 0.20;
const double final_test = 0.40;
const double maxGrade = 100.0, minGrade = 1.0;
//initialize arrays
string nonNumerical[studsize][strSize];
int numeric1[studsize][numSize];
double numeric2[studsize][courseSize][examSize];
char lettergrades[studsize][courseSize];
cout << fixed << showpoint << setprecision(2);
//opening files
ifstream inputFile;
inputFile.open("Project4_A04314548_Input.txt");
ofstream fout;
fout.open ("Project4_A04314548_Output.txt");
if( !( inputFile && fout))
{
cout << "Error opening file.\n";
}
cout << " Enter a number of students: ";
cin >> numstudents;
while( !(numstudents ==3))
{
cout << " error number of students must be 3. Enter again: ";
cin >> numstudents;
}
//take in string data from input file
for(int x =0; x< studsize; x++)
{
for(int y=0; y < strSize; y++)
{
if(y >= strSize)
break;
getline(inputFile, nonNumerical[x][y]);
strLength = nonNumerical[x][y].length();
if(strLength < minStrLength || strLength > maxStrLength)
{
fout << " The given string for nonNumerical [" << x << "][" << y <<
"] is not within the proper range of 1-100 characters." << endl;
fout << " Please fix the issue and rerun the program for a correct
output." << endl << endl;
continue;
}
}
}
//above put into input data function
//take in data from input file
for(int x=0; x<studsize;x++)
{
for(int y=0; y < numSize; y++)
{
if(y>=numSize)
break;
inputFile >> numeric1[x][y];
if( numeric1[x][y] < minint || numeric1[x][y] > maxint)
{
fout << "The given integer for numerical1[" << x << "][" << y <<
"]is not within the proper range of 1-100." << endl;
fout << " please fix the problem and rerun the program for a correct
output." << endl << endl;
break;
}
}
}
//above put into data function
// take in double data from input file
for( int x1=0; x1<studsize; x1++)
{
for(int x2=0; x2 < courseSize; x2++)
{
for(int x3=0; x3<(examSize-1);x3++)
{
if(x3 >=(examSize-1))
break;
inputFile >> numeric2[x1][x2][x3];
if( numeric2[x1][x2][x3] < minGrade || numeric2[x1][x2][x3] >
maxGrade)
{
cout << "The given value fro numeric2[" << x1 << "][" << x2
<< "][" << x3 << "] is not within the proper range of 1-100" << endl
<< "Please fix the issue and rerun the program for a correct
output." << endl;
break;
}
else if( x3 == 0)
scoreTotal += (numeric2[x1][x2][x3]* test1);
else if( x3== 1)
scoreTotal += (numeric2[x1][x2][x3]* test2);
else if( x3 == 2)
scoreTotal += (numeric2[x1][x2][x3]* test3);
else if( x3 == 3)
scoreTotal += (numeric2[x1][x2][x3]* test4);
else
scoreTotal += (numeric2[x1][x2][x3]* final_test);
}
numeric2[x1][x2][5] = scoreTotal; // final numeric grade
scoreTotal = 0;
if(x2 >=courseSize)
break;
if((numeric2[x1][x2][5] > maxGrade) || (numeric2[x1][x2][5] <
minGrade) )
{
cout << "Error in calculating grade. Please fix the issue
then rerun the program. ignore broken program!";
cout << endl << endl;
continue;
}
else if(numeric2[x1][x2][5] >= letterGrade_A)
lettergrades[x1][x2] = 'A';
else if(numeric2[x1][x2][5] >= letterGrade_B)
lettergrades[x1][x2] = 'B';
else if(numeric2[x1][x2][5] >= letterGrade_C)
lettergrades[x1][x2] = 'C';
else if(numeric2[x1][x2][5] >= letterGrade_D)
lettergrades[x1][x2] = 'D';
else
lettergrades[x1][x2] = 'F';
}
}
for(int a1=0; a1< studsize; a1++)
{ fout << nonNumerical[a1][0]<< endl;
fout << right << setw(35) << "Name of Student:\t";
fout << nonNumerical[a1][1] << endl;
fout << right << setw(35) << "Student ID:\t";
fout << nonNumerical[a1][2]<< endl;
fout << right << setw(35) << "Address:\t" ;
fout << nonNumerical[a1][3] << endl;
fout << right << setw(35) << "Telephone Number:\t";
fout << nonNumerical[a1][4] << endl;
fout << right << setw(35) << "Student Soc. Security:\t";
fout << nonNumerical[a1][5] << endl;
fout << right << setw(35) << "Age:\t";
fout << numeric1[a1][0] << endl;
fout << right << setw(35) << "Number of years at Texas State:\t";
fout << numeric1 [a1][1] << endl << endl;
for(int b1=0; b1 <courseSize; b1++)
{
fout << right << setw(35) << "Course number:\t";
fout << nonNumerical[a1][(b1+6)] << endl;
for(int c1= 0; c1 <(examSize-1); c1++)
{
fout << right << setw(32) << "Exam #" << (a1 +1) << ":\t";
fout << numeric2[a1][b1][c1] << endl;
}
fout << right << setw(35) << "Numerical grade:\t";
fout << numeric2[a1][b1][5] << endl;
fout << right << setw(35) << "Letter grade:\t";
fout << lettergrades[a1][b1] << endl;
if( numeric2[a1][b1][5] < 70)
{
fout << right << setw(14) << " Warning Note: Your grade is too low
and needs improvements!" << endl << endl;
}
else if ( numeric2[a1][b1][5] >= 95)
{
fout << right << setw(14) << " Appreciation Note: Congratulations,
Your performance is Excellent!" << endl << endl;
}
else
fout << endl;
}
fout << endl;
}
inputFile.close();
fout.close();
return 0;
}
Instead of using array
std::string nonNumerical[studsize][strSize];
use std::vector.
std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize));
Then, you can divide your code into as many functions as you need and pass the vectors to the functions.
void function1(std::vector<std::vector<std::string>>& nonNumerical)
{
...
}
and use it from main as:
int main()
{
...
std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize));
...
function1(nonNumerical);
...
}
first of all c++ send arrays by reference .
your question is not clear ... but if I have get it right, you should send two dimensional arrays like this :
void f1(int a[][20]) ;
just the point is that , you must specify second dimension .
You can pass any size and dimension of array with pointers like this:
myfunction1(string *nonNumerical)
{
string something=nonNumerical[0][0];
}
But don't forget: You can't ask the array's size directly. You must pass the size with the array somehow.
I'm working on an assignment for school. The code is supposed to read form a file and create an array, then sort the values of the array to output certain info. It works just fine as long as I have 3+ lines of info in the file. If not, I get the following error:
First-chance exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
Unhandled exception at 0x01305876 in Homework11.exe: 0xC0000005: Access violation reading location 0xcd71b288.
I can't figure out why, any help would be appreciated. Here's the code:
#include <iostream> //calls the information needed
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std; //sets all unmarked commands to std::
const int ARRSIZE = 1000;
struct Student
{
string firstName;
string lastName;
string id, temp;
double gpa;
};
int readArray(ifstream& ifile, Student arr[]);
void swapElements(Student arr[], int i, int j);
void sortArray(Student arr[], int numberInTheArray);
int main()
{ // Declares the needed variables
double sought, min, max;
int i, ival, returnvar, count = 0, mincount, maxcount;
string filename;
ifstream ifile;
Student arr[ARRSIZE];
cout << "Input File Name: ";//requesting the file name
cin >> filename;
ifile.open(filename.c_str());//opening the file
if (!ifile)//checking if it opened or not
{
cout << endl << "That file does not exist!" << endl;//informing the user it did
return 1;//not open and returning 1
}
cout << "Which number do you want to return? ";//requesting the desired number
cin >> ival;
i = ival - 1;
cout << endl;
returnvar = readArray(ifile, arr);
min = arr[0].gpa;
max = arr[0].gpa;
sought = arr[0].gpa;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
if (count == 0)
{
cout << "The file is empty!" << endl;
return 1;
}
cout << "Before Sort:" << endl;
cout << " Min GPA is " << min << " for " << arr[mincount].lastName << "." << endl;
cout << " Max GPA is " << max << " for " << arr[maxcount].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sortArray(arr, returnvar);
count = 0;
while (count < returnvar)
{
if (arr[count].gpa < min)
{
min = arr[count].gpa;
mincount = count;
}
if (arr[count].gpa > max)
{
max = arr[count].gpa;
maxcount = count;
}
if (count == i)
{
sought = arr[count].gpa;
}
count++;
}
cout << "After Sort:" << endl;
cout << " Array[0] GPA is " << min << " for " << arr[0].lastName << "." << endl;
cout << " Array[" << (returnvar - 1) << "] GPA is " << max << " for " << arr[(returnvar - 1)].lastName << "." << endl;
if (returnvar < ARRSIZE)
{
cout << " WARNING: Only " << returnvar << " numbers were read into the array!" << endl;
}
if (i >= returnvar)
{
cout << " There aren't that many numbers in the array!" << endl << endl;
}
else if (i > ARRSIZE)
{
cout << " " << i << " is bigger than " << ARRSIZE << "!" << endl << endl;
}
else if (i < returnvar)
{
cout << " Value " << ival << " is " << sought << " for " << arr[i].lastName << "." << endl << endl;
}
return 0;
}
int readArray(ifstream& ifile, Student arr[])
{
int counter = 0;
while ((ifile) && (counter <= ARRSIZE))
{
ifile >> arr[counter].firstName;
ifile >> arr[counter].lastName;
ifile >> arr[counter].id;
ifile >> arr[counter].gpa;
counter++;
}
return (counter - 1);
}
void sortArray(Student arr[], int numberInTheArray)
{
for (int i = 0 ; i < numberInTheArray - 1; i++)
{
for (int j = 0 ; j < numberInTheArray - 1; j++)
{
if ( arr[j].gpa > arr[j + 1].gpa)
{
swapElements(arr, j, j+1);
}
}
}
}
void swapElements(Student arr[], int i, int j)
{
Student temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Please ignore the insanity and comments. Like I said, for an entry level course.
Try replacing counter <= ARRSIZE with counter < ARRSIZE (a rule of thumb in C is: never use <= in operations related to container sizes).
EDIT: also in your main(), you must check that i < ARRSIZE (equivalently, return error if i >= ARRSIZE). At present you seem to accept the case i == ARRSIZE, which is also wrong. And finally, readArray should return counter (that is, one more than the last written index).
so my problem is that i have to read from a file that looks like this
input_M1
1,2
9,5
4,1
input_M2
3,2,6,1
4,1,7,8
of course I have to omit the "input_1" and "input_1", and i was able to do that and separate each matrix by itself in a string like this :
1,2
9,5
4,1
and this :
3,2,6.1
4,1,7,8
I was trying to make a dynamic array, i got the rows, with this
while(getline(ss,str1)){
row++;
}
and it prints the number of rows. However, when I do that for the columns :
while(getline(ss,str1,',')){
colmn++;
}
and when I print it out nothing appears.
and here is my whole code :
ifstream inFile;
inFile.open("c:\\Games\\crap.txt");
if (inFile.is_open()){
cout << "File successfully opened" << endl;
}
else{
cout << "Error opening file" << endl;
}
string sMain,sCutOut,firstMatrix,secondMatrix;
int counter = 1;
while(getline(inFile,sMain)){
sCutOut+=(sMain+'\n');
}
//cout << sCutOut << endl;
sCutOut = sCutOut.substr( sCutOut.find("1")+1,sCutOut.length() );
//cout << sCutOut << endl;
firstMatrix = sCutOut.substr( 0,sCutOut.find("input_M2") );
//cout << firstMatrix << endl;
secondMatrix = sCutOut.substr( sCutOut.find("_")+3,sCutOut.length() );
//cout << secondMatrix << endl;
istringstream ss (firstMatrix);
istringstream sn (secondMatrix);
string str1,str2,str3;
int row=0,colmn=0;
while(getline(ss,str1,'\n')){
//cout << str1 << '\n';
row++;
//cout << row << " ";
}
while(getline(ss,str2,',')){
cout << str2 << '\n';
colmn++;
cout << colmn << " ";
}
also, i get this when I try to print out the (firstMatrix) with out the new line I get this :
1,29,54,1
I used C++11 Regular expression library and I applied a simple regular expression to strip off the input_M? lines.
// under g++ 4.8.1 compile:
// $ g++ apply_regex.cpp -std=c++11 -lboost_regex -o apply_regex
#include <fstream>
#include <iostream>
// #include <regex> not implemented yet in g++ 4.8.1 (c++11 standard)
#include <boost/regex.hpp> // using boost libraries
using namespace std;
using boost::regex;
using boost::regex_replace;
int main() {
ifstream inFile;
inFile.open("crap.txt");
if (inFile.is_open()) {
cout << "File successfully opened" << endl;
}
else {
cout << "Error opening file" << endl;
}
string sMain, sCutOut;
while(getline(inFile,sMain)) {
sCutOut+=(sMain+'\n');
}
inFile.close();
cout << "Read lines from crap.txt" << endl;
cout << sCutOut;
// regular expression checks from input_M1 or input_M2 etc..
regex txt_regex("input_M[1-9]+");
string result = regex_replace(sCutOut, txt_regex, "");
cout << "After applying regular expression \"input_M[1-9]+\":" << endl;
cout << result;
return 0;
}
The result of the above code is:
$ ./apply_regex
File successfully opened
Read lines from crap.txt
input_M1
1,2
9,5
4,1
input_M2
3,2,6,1
4,1,7,8
After applying regular expression "input_M[1-9]+":
1,2
9,5
4,1
3,2,6,1
4,1,7,8
Update : i made the matrix into one line and then made them delimited with commas and that is it !
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
#include<sstream>
#include<vector>
#include<string>
#include<stdlib.h> using namespace std;
int main() {
cout << "Hello! today i'm gonna help you to multiply 2 matrices." << endl;
cout << "But first, we need to discuss the format of the file" << endl;
cout << "help me with the format so i can help you to multiply !" << endl;
cout << "this is how i like the format of the file to be : " << endl;
cout << "--------------------------------" << endl;
cout << "input_M1" << endl;
cout << "number,number," << endl;
cout << "number,number" << endl;
cout << "input_M2" << endl;
cout << "number,number," << endl;
cout << "number,number," << endl;
cout << "--------------------------------" << endl;
cout << "make sure that you put the comma at the end of each line to indicate the end of the line of the matrices [not the input_M1 or input_M2], Have fun !" << endl << endl;
string fileDirct = ""; string fileName = "";
cout << "Now, Enter the file directory, with 2 backslashs, i.e : 'C:\\\\program files'" << endl; cin >> fileDirct; cout << "and Enter the file name, followed by the file type, i.e : 'testData.txt'" << endl; cin >> fileName;
string file = fileDirct+"\\"+fileName; fileDirct = fileDirct.c_str(); ifstream infile;
infile.open(file.c_str());
//ifstream infile( "c:\\Games\\crap.txt");
string sLiner,sStoring,firstMatrix,secondMatrix,sTemp1,sTemp2;
while(infile){
getline( infile, sLiner );
sStoring+=(sLiner+'\n');
}
//cout << sStoring;
sStoring = sStoring.substr( sStoring.find("_")+3,sStoring.length() );
//cout << sStoring;
firstMatrix = sStoring.substr(0,sStoring.find("i"));
//cout << firstMatrix;
secondMatrix = sStoring.substr(sStoring.find("_")+3,sStoring.length());
//cout << secondMatrix;
istringstream ssMtrx1(firstMatrix);
istringstream ssMtrx2(secondMatrix);
istringstream ss(firstMatrix);
istringstream ssk(secondMatrix);
ssMtrx1 >> sTemp1;
istringstream ssR_C1(sTemp1);
int colmn=0;
while(getline(ssR_C1,sTemp2,',')){
colmn++;
}
//cout << colmn;
if (colmn > 6 ){
cout << "the matrix has more than 6 columns";
}
sTemp1.clear();
int row=0;
while(getline(ssMtrx1,sTemp1)){
row++;
}
//cout << row;
if (row > 6 ){
cout << "the matrix has more than 6 rows";
}
//--------------------------------------------------------------------------------
sTemp1.clear();
ssMtrx2 >> sTemp1;
istringstream ssR_C2(sTemp1);
int colmn2=0;
while(getline(ssR_C2,sTemp2,',')){
colmn2++;
}
//cout << colmn2;
if (colmn2 > 6 ){
cout << "the matrix has more than 6 columns";
}
sTemp1.clear();
int row2=0;
while(getline(ssMtrx2,sTemp1)){
row2++;
}
row2 = row2-1;
//cout << row2;
if (row2 > 6 ){
cout << "the matrix has more than 6 rows";
}
//=========================================================================
int** Mtrx1Arry = new int*[row];
for(int i = 0; i < row; ++i){
Mtrx1Arry[i] = new int[colmn];
}
int** Mtrx2Arry = new int*[row2];
for(int i = 0; i < row2; ++i){
Mtrx2Arry[i] = new int[colmn2];
}
sTemp1.clear();
sTemp2.clear();
while(getline(ss,sTemp1,'\n')){
sTemp2+=sTemp1;
}
//cout << sTemp2;
istringstream ss1(sTemp2);
sTemp1.clear();
for(int i = 0; i < row;i++){
for(int j = 0; j < colmn;j++){
getline(ss1,sTemp1,',');
Mtrx1Arry[i][j]=atoi(sTemp1.c_str());
}
}
for(int i = 0; i < row;i++){
for(int j = 0; j < colmn;j++){
//cout << Mtrx1Arry[i][j] << " ";
}
}
//-------------------------------------------------------------
sTemp1.clear();
sTemp2.clear();
while(getline(ssk,sTemp1,'\n')){
sTemp2+=sTemp1;
}
//cout << sTemp2;
istringstream ss2(sTemp2);
sTemp1.clear();
for(int i = 0; i < row2;i++){
for(int j = 0; j < colmn2;j++){
getline(ss2,sTemp1,',');
Mtrx2Arry[i][j]=atoi(sTemp1.c_str());
}
}
for(int i = 0; i < row2;i++){
for(int j = 0; j < colmn2;j++){
//cout << Mtrx2Arry[i][j] << " ";;
}
}
//=============================================================================
// mtrx1[x][y] and mtrx2[z][y] : y has to == z // while the values are under 6
if( (colmn <= 6) && (colmn2 <= 6) && (row <= 6) && (row2 <= 6)){
if (colmn==row2){
cout << "the two matrices can be multiplied " << endl;
cout << "the new matrix will be : " << row << " x " <<colmn2 << endl;
int** MtrxRsltArry = new int*[row];
for(int i = 0; i < row; ++i){
MtrxRsltArry[i] = new int[colmn2];
}
for(int i = 0; i < row;i++){
for(int j = 0; j < colmn2;j++){
MtrxRsltArry[i][j]=0;
for(int k=0; k < colmn; k++){
MtrxRsltArry[i][j]=MtrxRsltArry[i][j]+(Mtrx1Arry[i][k]*Mtrx2Arry[k][j]);
}
}
}
for(int i = 0; i < row;i++){
//cout << endl;
for(int j = 0; j < colmn2;j++){
//cout << MtrxRsltArry[i][j] << ",";;
}
}
// cout << endl;
ofstream outFile;
string cat = fileDirct+"\\result.txt";
outFile.open(cat.c_str());
cout << "the result.txt has been created at : " << fileDirct << endl;
outFile << "result_M";
for(int i = 0; i < row;i++){
outFile << endl;
for(int j = 0; j < colmn2;j++){
outFile << MtrxRsltArry[i][j] << ",";
}
}
}
else{
cout << "the two matrices can not be multiplied ";
}
}
for(int i = 0; i < colmn; ++i) {
delete [] Mtrx1Arry[i];
}
delete [] Mtrx1Arry;
for(int i = 0; i < colmn2; ++i) {
delete [] Mtrx2Arry[i];
}
delete [] Mtrx2Arry;
return 0; }
I have a program that takes in a set of 16 numbers and prints them out in a grid of 4x4. I must then check each row, column and diagonal add up to the same number, however I can't do this part, as I have no idea how that would work. Can anyone help?
current code:
void getNumbers(int numbers[]){
int idx;
for(int x = 0; x < 17; x++){
cout << "Please enter a number: " << endl;
cin >> idx;
numbers[x] = idx;
}
cout << " " << numbers[0] << " " << numbers[1] << " " << numbers[2] << " " << numbers[3] << endl;
cout << " " << numbers[4] << " " << numbers[5] << " " << numbers[6] << " " << numbers[7] << endl;
cout << " " << numbers[8] << " " << numbers[9] << " " << numbers[10] << " " << numbers[11] << endl;
cout << " " << numbers[12] << " " << numbers[13] << " " << numbers[14] << " " << numbers[15] << endl;
}
remove any syntax error if you see, the overall code must work! Enjoy ;-)
bool magicSquare(){
int idx;
int numbers[4][4];
cout << "Please enter your numbers: " << endl;
for(unsigned int i=0; i<4; i++) {
for(unsigned int j=0; j<4; j++) {
cin >> idx;
numbers[i][j] = idx;
}
}
// Checking
for(unsigned int i=0; i<4; i++) {
int row_sum = 0;
for(unsigned int j=0; j<4; j++) {
row_sum+= numbers[i][j];
}
int col_sum = 0;
for(unsigned int j=0; j<4; j++) {
col_sum+= numbers[j][i];
}
int diag_sum_left = numbers[0][0] + numbers[1][1] + numbers[2][2];
int diag_sum_right = numbers[0][2] + numbers[1][1] + numbers[2][0];
if ((col_sum != 15) ||
(row_sum !=15) ||
(diag_sum_left != 15) ||
(diag_sum_right != 15) )
return false;
}
cout << "Your answer is correct:" << endl;
for(unsigned int i=0; i<4; i++) {
for(unsigned int j=0; j<4; j++)
cout << numbers[i][j] << "\t";
cout << endl;
}
return true;
}
You can just write all the sums and the rules directly
Like this:
int horizontal1 = numbers[0]+ numbers[1]+ numbers[2]+ numbers[3];
int horizontal2 = numbers[4]+ numbers[5]+ numbers[6]+ numbers[7];
int horizontal3 = numbers[8]+ numbers[9]+ numbers[10]+numbers[11];
int horizontal4 = numbers[12]+numbers[13]+numbers[14]+numbers[15];
int vertical1 = numbers[0]+numbers[4]+numbers[8]+ numbers[12];
int vertical2 = numbers[1]+numbers[5]+numbers[9]+ numbers[13];
int vertical3 = numbers[2]+numbers[6]+numbers[10]+numbers[14];
int vertical4 = numbers[3]+numbers[7]+numbers[11]+numbers[15];
int diagonal1 = numbers[0]+numbers[5]+numbers[10]+numbers[15];
int diagonal2 = numbers[3]+numbers[6]+numbers[9]+ numbers[12];
// The result of check would be in this variable
bool result = horizontal1 == horizontal2 &&
horizontal1 == horizontal3 &&
horizontal1 == horizontal4 &&
horizontal1 == vertical1 &&
horizontal1 == vertical2 &&
horizontal1 == vertical3 &&
horizontal1 == vertical4 &&
horizontal1 == diagonal1 &&
horizontal1 == diagonal2;
Put how to check aside, you have something wrong in the posted code:
You mentioned that you have 16 numbers but you are actually asking for 17. If your numbers array has size = 16, then you will have index out of bound error.
for(int x = 0; x < 17; x++){
//^^^should be 16, put them into numbers array with numbers[0] to numbers[15]
cout << "Please enter a number: " << endl;
cin >> idx;
numbers[x] = idx;
}
For checking, the brute force way is to check for rows,columns then diagonal separately.