So this is a program I wrote for a CS lab in my class. It was modified so that it would take in input from a text file and output to another text file. After it does the calculations, it asks the user if they want to rerun the program, which is just a while loop in main. Why do I get this error when I the program reruns?
Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffeb1d82bc8)
it occurs at this line in the getPints function:
bloodInFile >> a[i];
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
#include <fstream>
using namespace std;
const int MAX_HOURS = 7;
void getPints(double a[], int h);
double getAverage(double a[], int h);
double getHigh(double a[], int h);
double getLow(double a[], int h);
void displayInfo(double a, double b, double c);
int main()
{
string again = "yes";
double pints[MAX_HOURS];
double getHigh(double pints[], int MAX_HOURS);
while (again == "yes")
{
getPints(pints, MAX_HOURS);
getHigh(pints, MAX_HOURS);
displayInfo(getAverage(pints, MAX_HOURS), getHigh(pints, MAX_HOURS), getLow(pints, MAX_HOURS));
cout << "Do you want to run again (yes or no)? ";
cin >> again;
}
return 0;
}
void getPints(double a[], int h)
{
int i;
ifstream bloodInFile;
bloodInFile.open("bloodDrive.txt");
if (!bloodInFile)
cout << "Cannot open file." << endl;
while (!bloodInFile.eof())
{
bloodInFile >> a[i];
i++;
}
bloodInFile.close();
}
double getAverage(double a[], int h)
{
int i;
double totalPints = 0;
double averagePints;
for (i = 0; i <= h - 1; i++)
totalPints = totalPints + a[i];
averagePints = totalPints / i;
return averagePints;
}
double getHigh(double a[], int h)
{
int i;
double highest = a[0];
for (i = 1; i < h; i++)
{
if (a[i] > highest)
highest = a[i];
}
return highest;
}
double getLow(double a[], int h)
{
int i;
double lowest = a[0];
for (i = 1; i < h; i++)
{
if (a[i] < lowest)
lowest = a[i];
}
return lowest;
}
void displayInfo(double a, double b, double c)
{
ofstream bloodOutFile;
bloodOutFile.open("bloodResults.txt");
bloodOutFile << "Average pints: " << setprecision(1) << showpoint<< fixed << a << endl;
bloodOutFile << "Highest pints: " << setprecision(1) << showpoint<< fixed << b << endl;
bloodOutFile << "Lowest pints: " << setprecision(1) << showpoint<< fixed << c << endl;
}
Check that you are not out of bound of array a in function getPints add check here
while (!bloodInFile.eof())
{
if(i >= h)
break;
bloodInFile >> a[i];
i++;
}
Because if you can have more lines that MAX_HOURS in bloodDrive.txt file. Also I don't see that you initialize i somewhere i suppose it should be equal to 0 (i=0), so you're function should looks like that
void getPints(double a[], int h)
{
int i = 0;
ifstream bloodInFile;
bloodInFile.open("bloodDrive.txt");
if (!bloodInFile)
cout << "Cannot open file." << endl;
while (!bloodInFile.eof())
{
if(i > h)
break;
bloodInFile >> a[i];
i++;
}
bloodInFile.close();
}
P.S. as #JonathanLeffler said (and I agree with him 100%) it's better to use dynamic array (vector e.g.) for such problem when you don't know how much input could be.
Related
I'm trying to write a C++ program that:
Creates an array_1 of size n and fills it following the formula
x(i) = x(0) + h*i where n, x(0) and h are input parameters;
Creates an array_2 of size l=n+1 and fills it following the
formula x(i) = ((b-a)/n)*i+a , where a, b are input parameters;
Creates an array_sin of size l=n+1 and fills it with the sine of
the elements of array_2.
I decided to do these three steps in three separate void functions. Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void fillarr1 (double ar_x[], int n, double x_0, double h);
void fillarr2 (double ar_y[], double a, double b, int n, int l);
void Sin (double ar_y[], double sine_[], int l);
int main ()
{
int n, i;
double a, b, h, x_0;
cout << "Number of points \n";
cin >> n;
int l=n+1;
double *x = new double(n); //array_1
double *y = new double(l); //array_2
double *sine = new double(l); //array_3
cout << "Separation between points \n";
cin >> h;
cout << "x(0) = ";
cin >> x_0;
fillarr1 (x, n, x_0, h);
cout << "\na = ";
cin >> a;
cout << "\nb = ";
cin >> b;
fillarr2 (y, a, b, n, l);
cout << "\nsin \n";
Sin(y, sine, l);
cout << "\n\n\n";
for (i=0; i<n; i++)
{
cout << x[i] << "\t";
}
cout << "\n\n\n";
for (i=0; i<l; i++)
{
cout << y[i] << "\t";
}
cout << "\n\n\n";
for (i=0; i<l; i++)
{
cout << sine[i] << "\t";
}
delete [] x;
delete [] y;
delete [] sine;
return 0;
}
void fillarr1 (double ar_x[], int n, double x_0, double h)
{
int i;
for (i=0; i<n; i++)
{
ar_x[i]=x_0+h*i;
cout << ar_x[i] << "\t";
}
}
void fillarr2 (double ar_y[], double a, double b, int n, int l)
{
int i;
double h_;
h_=(b-a)/(n);
for (i=0; i<l; i++)
{
ar_y[i]=a+h_*i;
cout << ar_y[i] << "\t";
}
}
void Sin(double ar_y[], double sine_[], int l)
{
int i;
for(i=0;i<l;i++)
{
sine_[i]=sin(ar_y[i]);
cout << sine_[i] << "\t";
}
}
I'm also trying to print the elements of the arrays both in the void functions and in the main. It appears that, after the function calls, the original dynamic arrays passed to the void functions are filled with random values. Furthermore, the process exits with return value 3221226356.
Here is an output example:
output
I really don't know how to fix it, any help would be very appreciated.
You're not creating arrays of double here:
double *x = new double(n); //array_1
double *y = new double(l); //array_2
double *sine = new double(l); //array_3
but single values, you want something like:
double *x = new double[n]; //array_1
double *y = new double[l]; //array_2
double *sine = new double[l]; //array_3
The program should read n resistances and a voltage from the keyboard and then calculate the equivalent resistance and the current.
My problem is that it calculates based only on the last entered resistance.
Is it possible to declare a method inside a function? or should I give up this completely unpractical approach
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
class rez {
float r;
public:
void set(int n);
float val() { return r; }
};
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r;
}
}
float serie(rez r1,int n)
{
float s=0;
int i;
for (i = 1; i <= n; i++)
{
s = s+ r1.val();
}
return s;
}
float para(rez r1, int n)
{
float s = 0;
int i;
for (i = 1; i <= n; i++)
{
s = s + (1/r1.val());
}
return 1/s;
}
int main()
{
char c, k = 'y'; // 'c' selects series or para
rez r1;
int n;
cout << "number of resis:";
cin >> n;
cout << endl;
while (k != 'q')
{
r1.set(n);
float i, u;
cout << "\n Vdc= ";
cin >> u;
cout << endl;
cout << "series or para(s/p)?"<<endl;
cin >> c;
switch (c)
{
case('s'):cout <<"\n equiv resistance = "<< serie(r1,n)<<endl;
i = u / serie(r1, n);
cout << "curr i = " << i << " amp";
break;
case('p'):cout << "\n equiv res = " << para(r1, n)<<endl;
i = u / para(r1, n);
cout << "cur i = " << i << " amp";
break;
}
cout <<endl<< "\n another set?(y/q)?"<<endl;
cin >> k;
}
return 0;
}
It is because when you read in the resistances you are setting the value of the total resistance each time not adding to the total resistance.
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r; // <- this sets the value of r, it does not add to it
}
}
To fix this you should create a temporary variable to store the input resistance and then add it to the total resistance
void rez :: set(int n)
{
int i;
for (i = 1; i <= n; i++)
{
float input;
cout << "R" << i << "=";
cin >> input;
r += input;
}
}
I have a simple program that is calculating factorials, permutations and combinations. I feel good about my math but for whatever reason I cannot get this program to execute. Full disclosure I am new student to C++. Here is my code:
#include <iostream>
using namespace std;
int factorial(int);
int permutations(int, int);
int combinations (int ,int);
void perms_and_combs(int, int, int&, int&);
int numPerms;
int numCombs;
int main() {
int factorialVal;
cout << "enter an int!\n";
cin >> factorialVal;
cout << "The factorial of " << factorialVal << " is " << factorial(factorialVal) << endl;
int permVal1;
int permVal2;
do {
cout << "Input a two values: ";
cin >> permVal1;
cout << ", ";
cin >> permVal2;
} while ( permVal1 < 0 || permVal2 > permVal1);
cout << "test"; // This line doesn't get executed
perms_and_combs(permVal1, permVal2, numPerms, numCombs);
cout << "Number of permutations: "<<numPerms << ". Number of combinations: " << numCombs;
return 0;
}
int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}
int permutations (int n, int k) {
int result;
int denominator = n-k;
cout << denominator;
result = (factorial(n)/factorial(denominator));
return result;
}
int combinations (int n, int k) {
int result;
result = permutations(n, k) * (1/factorial(k));
return result;
}
void perms_and_combs(int n, int k, int& numPerms, int& numCombs) {
numPerms = permutations(n, k);
numCombs = combinations(n, k);
return;
}
So for my problem I need to have a dynamically allocated array that is to be created in the main function and populated in another function. The issue I'm having is that I then need to use that array in other functions and my array has no value after I populate it in my function (or at least this seems to be the case) Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
//prototypes
int getNumber();
void getMovieData(int *ptrToArray, int arraySize);
void sort(int *ptrToArray, int arraySize);
double getAverage(int *ptrToArray, int arraySize);
void print(int *ptrToArray, int arraySize);
int main()
{
int stuNum = 0;
int* stuArray;
stuArray = new int[stuNum];
getMovieData(stuArray, stuNum);
cout << "--- Here is the data you entered ---" << endl;
print(stuArray, stuNum);
sort(stuArray, stuNum);
cout << "--- Here is the data you entered sorted ---" << endl;
print(stuArray, stuNum);
cout << fixed << setprecision(2);
cout << "Here is the average of your survey" << getAverage(stuArray, stuNum) << endl;
system("pause");
return 0;
}
int getNumber()
{
int userNum;
cin >> userNum;
while (userNum <= 0)
{
cout << "Error number must be greater than zero." << endl;
cin >> userNum;
}
return userNum;
}
void getMovieData(int *ptrToArray, int arraySize)
{
cout << "Enter the number of students being surveyed: ";
arraySize = getNumber();
for (int i = 0; i < arraySize; i++)
{
cout << "Enter the movies seen by Student " << i + 1 << ": ";
ptrToArray[i] = getNumber();
}
return;
}
void sort(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
for (int j = 0; j < arraySize - 1; j++)
{
if (ptrToArray[j] > ptrToArray[j + 1])
{
int temp = ptrToArray[j];
ptrToArray[j] = ptrToArray[j + 1];
ptrToArray[j + 1] = temp;
}
}
}
}
double getAverage(int *ptrToArray, int arraySize)
{
int total = 0;
for (int i = 0; i < arraySize; i++) { total = total + ptrToArray[i]; }
return total;
}
void print(int *ptrToArray, int arraySize)
{
for (int i = 0; i < arraySize; i++) { cout << ptrToArray[i] << "\t"; }
cout << endl;
}
You are allocating an array with zero elements. Change the value of stuNum to a positive number representing the number ints you need.
Ok so everything is working except that the sorted data is sometimes outputting whole numbers rather than a decimal number. This seems like an easy mistake to fix, but I can't find it!
#include <iostream>
using namespace std;
void input (double x[], int length);
void copy (double source[], double dest[], int length);
void sort (double x[], int length);
void display (double x[], int length);
int main()
{
double data[20];
double sdata[20];
int itemcount;
cout << "Enter data item count <1-20>" << endl;
cin >> itemcount;
if ((itemcount < 1) || (itemcount > 20))
{
cout << "Class size is NOT within required range. The required range is 1 to 20." << endl;
cout << "Bye." << endl;
return (0);
}
input (data, itemcount);
cout << "Original Data:" << endl;
copy (data, sdata, itemcount);
display (sdata, itemcount);
sort (sdata, itemcount);
cout << "Sorted Data" << endl;
display (sdata, itemcount);
}
void input (double x[], int length)
{
int i;
for (i=0; i < length; i++)
{
cout << "Enter score" << endl;
cin >> x[i];
}
}
void copy (double source[], double dest[], int length)
{
int i;
for (i=0; i < length; i++)
{
dest[i] = source[i];
}
}
void sort (double x[], int length)
{
int i, temp;
bool swapdone = true;
while (swapdone)
{
swapdone = false;
for (i=0; i < length-1; i++)
{
if (x[i] > x[i+1])
{
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
swapdone = true;
}
}
}
}
void display (double x[], int length)
{
int i;
for (i=0; i < length; i++)
{
cout << x[i] << " ";
}
cout << endl;
}
In an example run, the result is:
Enter data item count <1-20>
5
Enter score
30.41
Enter score
63.25
Enter score
62.47
Enter score
40.25
Enter score
310.41
Original Data:
30.41 63.25 62.47 40.25 310.41
Sorted Data
30.41 40.25 62 63 310.41
temp should be a double, not an int, if you don't want things you assign to it to become integers.
If you use "i" only as counter then you can declare it inside the for loop such as
for (int i=0;i<length;i++)
This will save some trouble. Anyway,
Change
int i, temp;
to
int i;
double temp;
Double means it can hold decimal numbers, integer means whole numbers. When you are swapping around to do the bubble sort, it is converting your double to integer type. Your compiler should given a type conversion error, but should compile.
Check
int i, temp;
temp must be double!
Try this:
double tmp;
std::cout << ios_base::setpercision(3) << tmp;