I have a function which returns a bool variable. Then I used 2 if statements to print something depending on if the bool variable is true or false. The system prints out segmentation fault instead which is strange since I declared the variable at the beggining as false, so it would make more sense that the program always printed the false statement. The only thing I can think of is that maybe I write the if statement incorrectly?? is there a certain way to write an if statement for a boolean variable?
Here is the input
Please enter name of the input file: 40.txt Please enter the prefered sum 1000
Here is the output
There were 1600 checks made to find the products of your desired sum and Segmentation fault (core dumped)
Here are the if statements but I will add the whole code below
if(!found)
{
cout << " the program did not find any matches. try again. ";
}
if(found)
{
cout << "the two numbers that add to your sum are " << n1 << " and " << n2 << ". These were found in position " << pos1 << " and " << pos2;
}
Here's the whole code
#include <iostream>
#include <fstream>
using namespace std;
int x, i, n1, n2, pos1 = 0, pos2 = 0, accesses = 0;
int readSortedArray(int array[20], int count, istream& infile)
{
count = 0;
while (infile >> array[count])
{
count++;
}
return count;
}
bool findproducts(int array[20],
int& n1,
int& n2,
int count,
int& accesses,
bool found,
int& pos1,
int& pos2)
{
int sum;
cout << "Please enter the prefered sum ";
cin >> sum;
for (i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for (x = 0; x < count; x++)
{
pos2++;
accesses++;
n2 = array[x];
if (sum == n1 + n2)
{
found = true;
i = count;
x = count;
return true;
}
}
}
}
int main()
{
int array[20];
int answer, count = 0;
bool found = false;
std::string input_filename;
ifstream infile;
cout << "Please enter name of the input file: ";
cin >> input_filename;
infile.open(input_filename.c_str());
if (!infile)
{
cout << "Could not open input file one\n";
return 0;
}
count = readSortedArray(array, count, infile);
found = findproducts(array, n1, n2, count, accesses, found, pos1, pos2);
cout << "There were " << accesses << " checks made to find the products of your desired sum and" << endl;
if (!found)
{
cout << " the program did not find any matches. try again. ";
}
if (found)
{
cout << "the two numbers that add to your sum are " << n1 << " and " << n2 << ". These were found in position " << pos1 << " and " << pos2;
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire