crash when reading from a file - c++

first of all, i'd like u to know that im a college student (our syllabus in programming is not that advanced yet)(Btw im not asking for answers to my assignments etc, im just practicing).
Ok so i have 2 problems
Some function in my code changes the value of my array (when i dont want it to)
I really have no idea, but it seems that getting some values from a file to store into my array crashes the program, furthermore, after fiddling a bit with the code (i have no idea what changed), it no longer crashes during the said part, BUT it still crashes at the end of the code execution..
i hope u guys could help me, i've been searching whole day long.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void readFile (float x[], int &y) {
ifstream load;
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
load.open(filename.c_str());
while (!load.eof()) {
load >> x[y];
y++;
}
if (!load) {
cout << "asd";
}
}
void computeC (float x[], int y, float z[]) {
int v=0;
for (v=0; v<=y; v++) {
z[v] = (5 * (x[v] - 32)/9);
}
}
float average (float x[], int y) {
int v=0;
float sum=0;
for (v=0; v<=y; v++) {
sum += x[v];
}
return sum / v;
}
void grade (float x[], char grades[], int y, int &hi, int &med, int &lo) {
int v=0;
hi = med = lo = 0;
for (v=0; v<=y; v++) {
if ( x[v] >= 35) {
grades[v] = 'H';
hi++;
}
else if ( (x[v] < 35) && (x[v] >= 20) ) {
grades[v] = 'M';
med++;
}
else if ( x[v] < 20 ) {
grades[v] = 'L';
lo++;
}
}
}
void writeFile (float x[], float y[], int z, char w[]) {
ofstream save;
int v=0;
for (v=0; v <= z; v++) {
cout << "C(Celcius)" << left << setw(5);
cout << "F(Farenheit)" << left << setw(5);
cout << "Description\n";
cout << right << setw(7) << y[v];
cout << left << setw(8) << x[v];
cout << left << setw(8) << w[v];
}
}
int main(int argc, char** argv) {
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
readFile (F, ctr);
computeC (F, ctr, C);
ave = average (C, ctr);
grade (C, grades, ctr, high, medium, low);
cout << "Average of the temperatures: " << ave << endl;
cout << "Number of high temperatures: " << high << endl;
cout << "Number of medium temperatures: " << medium << endl;
cout << "Number of low temperatures: " << low << endl;
//writeFile (F, C, ctr, grades);
return 0;
}
(Code from https://drive.google.com/file/d/0BxeZTCUL3Q4oZHlqWFdjMDZub0E/view?usp=sharing)

Without checking the whole code I can directly think of some parts of the code.
Let me start with
while (!load.eof()) {
load >> x[y];
y++;
}
Where you write more values than x[] can hold and your program will crash in that case.
Make sure to only write to your array up to the maximum allocated memory.
The problem is that !load.eof() will not do what you expect it to do as it will be read from beyond the end of the file. It will execute your loop one more time too much.
Second:
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
ctr is 0 so you declare Arrays of F, c and grades with 0 elements. That's not very clever ;) You can't read or write from them.

Related

My code's display for reading from a file is not working as intended

So for my program It is suposed to read from a file and display my information but the display is misbehaving. I have asked my collegues and they are unsure and I even asked my professor but he was unsure of what was causing the error. If anyone could help me I would be very very thankful and honnostly amazed
//LIBRARIES
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <string>
#include <cstring>
#include <thread>
#include <stdexcept>
#include <limits>
#include <cctype>
using namespace std;
//STORED ARRAY NAMES AND FUNCTION NAMES
int fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final);
float pointAverage (float theScore[], float numberOfGames);
int teamsScoredForty (float theScore[], int gameNum);
int savedMax (float theScore[], int gameNum);
int savedMin (float theScore[], int gameNum);
void printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum);
void finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty,
float averagePoints, int maxSavedInfo, int minSavedInfo);
//START OF MAIN
int
main ()
{
ifstream final;
float theScore[100];
string teamWin[100];
string teamLose[100];
int gameNum;
float numberOfGames;
float averagePoints;
int teamsOverForty;
int maxSavedInfo;
int minSavedInfo;
gameNum = fillArrays (teamWin, teamLose, theScore, final);
numberOfGames = gameNum;
averagePoints = pointAverage (theScore, numberOfGames);
teamsOverForty = teamsScoredForty (theScore, gameNum);
maxSavedInfo = savedMax (theScore, gameNum);
minSavedInfo = savedMin (theScore, gameNum);
printStoredInformation (teamWin, teamLose, theScore, gameNum);
finalDisplay (theScore, teamWin, teamLose, teamsOverForty,
averagePoints, maxSavedInfo, minSavedInfo);
return 0;
}
//FINAL DISPLAY OF INFORMATION
void
finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty[],
float averagePoints, int maxSavedInfo, int minSavedInfo)
{
cout << "AVERAGE = " << averagePoints << endl;
cout << "TEAMS WHO SCORED OVER 40 POINTS IN ONE GAME = " << teamsOverForty << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE MOST POINTS IN ONE GAME" << endl;
cout << "WINNERS = " << teamWin[maxSavedInfo] << endl;
cout << "LOSERS = " << teamLose[maxSavedInfo] << endl;
cout << "FINAL SCORE OF WINNERS" << theScore[maxSavedInfo] << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE LEAST POINTS AND STILL WON" << endl;
cout << "WINNERS = " << teamWin[minSavedInfo];
cout << "LOSERS = " << teamLose[minSavedInfo];
cout << "FINAL SCORE OF WINNERS = " << theScore[minSavedInfo];
cout << endl;
}
//INFORMATION STORAGE FOR ARRAYS
int
fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final)
{
int i = 0;
final.open ("superbowl.dat");
while (!final.eof ())
{
getline (final, teamWin[i]);
getline (final, teamLose[i]);
final >> theScore[i];
final.ignore (1, '\n');
i += 1;
}
final.close ();
return i;
}
//FUNCTION TO FIND AVERAGE OF THE TEAMS SCORE
float
pointAverage (float theScore[], float numberOfGames)
{
float sum;
float avg;
for (int i = 0; i < numberOfGames; i++)
{
sum = sum + theScore[i];
}
avg = sum / numberOfGames;
return avg;
}
//FUNCTION FOR ALL THE TEAMS WHO SCORED MORE THEN FORTY
int
teamsScoredForty (float theScore[], int gameNum)
{
int teamSavedScoreOverForty = 0;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] > 40)
{
teamSavedScoreOverForty = teamSavedScoreOverForty + 1;
}
}
return teamSavedScoreOverForty;
}
//FUNCTION TO FIND WHICH TEAM SCORED MORE THEN ANY OTHER TEAM AND WON
int
savedMax (float theScore[], int gameNum)
{
int val = -1;
int idx;
for (int i = 0; i < gameNum; i++)
{
if (val < theScore[i])
{
val = theScore[i];
idx = 1;
}
}
return idx;
}
//FUNCTION TO FIND WHICH TEAM SCORED LESS THEN ANY OTHER TEAM AND WON
int
savedMin (float theScore[], int gameNum)
{
int val = theScore[0];
int idx;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] < val)
{
idx = i;
}
}
return idx;
}
//FINAL DISPLAY FUNCTION FOR ALL OF THE INFORMATION ABOVE
void
printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum)
{
int a = 1;
for (int i = 0; i < gameNum; i++)
{
cout << "SUPER BOWL " << a << endl;
cout << "NAME OF WINNING TEAM - " << teamWin[i] << endl;
cout << "NAME OF LOSING TEAM - " << teamLose[i] << endl;
cout << "TOTAL POINTS SCORED BY WINNERS - " << theScore[i] << endl;
cout << endl;
a = a + 1;
}
}
That is the main code that it is having errors with.
PackersChiefs35PackersRaiders33JetsColts16ChiefsVikings23ColtsCowboys16CowboysDolphins24DolphinsRedskins14
DolphinsVikings24SteelersVikings16SteelersCowboys21RaidersVikings32CowboysBroncos27Broncos27SteelersVikings
35SteelersRams31RaidersEagles2749ersBengals26RedskinsDolphins27RaidersRedskings3849ersDolphins38Bears
Patriots46GiantsBroncos39RedskinsBroncos4249ersBengals2049ersBroncos55GiantsBills20RedskinsBills37Cowboys
Bills52CowboysBills3049ersChargers49CowboysSteelers27PackersPatriots35BroncosPackers31BroncosFalcons34
RamsTitans23RavensGiants34Patriotsrams20BuccaneersRaiders48PatriotsPanthers32PatriotsEagles24Steelers
Seahawks21ColtsBears29GiantsPatriots17SteelersCardinals27SaintsColts31PackersSteelers31GiantsPatriots
21Ravens49ers34SeahawksBroncos43PatriotsSeahawks28BroncosPanthers24PatriotsFalcons34EaglesPatriots41
PatriotsRams13Chiefs49ers31BuccaneersChiefs31RamsBengals23
Between Each word is an enter, I am just not alloud to put it in on this website sadly. It says it looks like Spam
I tried to mess with the 2 different displays I have and I tried to even add more functions to kep things more organized but it did not work. I also spent a few hours trying to debug it.
In addition to the concerns expressed by other users in the comments, your output is broken because you have a typo in your input file on record 13. You repeated Bronco 27 twice and the file input function breaks because it expects two team names and then an integer. Instead it receives a team name followed by a number:
SUPER BOWL 12
NAME OF WINNING TEAM - Cowboys
NAME OF LOSING TEAM - Broncos
TOTAL POINTS SCORED BY WINNERS - 27
SUPER BOWL 13
NAME OF WINNING TEAM - Broncos
NAME OF LOSING TEAM - 27
TOTAL POINTS SCORED BY WINNERS - 0
//...

Creating program that takes 5 grades from the user and finds the lowest grade, and then outputs average grade after dropping the lowest grade entered

`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|

Why is my txt file not opening successfully? c++

I am trying to open the txt file I made for the rest of my code to successfully run. I am using c++ and xcode is the environment. When I run my code, I get this:
error in opening studentScore8.txt
And below that is the correct formatting for the table but weird numbers are there. I am confident that the location for the file is correct, and I am not seeing any issues in my code besides
printGrade(oneScore, average);
in the main function, which xcode is saying that the parameters oneScore and average are not initialized, but I thought I already did that above.
Does anyone know what the issue could be? This is a lab for my comp sci class, and my teacher doesn't seem to know what the issue is either. I am thinking it has something to do with xcode or my computer itself, but I am not sure. The entire code is below.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
#define inFile "/Users/spacecowboy/Desktop/cis/cis/lab 8/studentScore8.txt"
const int MAX_SIZE = 4;
void readStuData (ifstream& rss, int scores[], int id[], int& count, bool& tooMany);
float mean(int scores[], int count);
void printTable(int scores[], int id[], int count);
void printGrade(int oneScore, float average);
int main() {
ifstream rss;
// void printTable(scores, id, count);
// float mean(int scores, int count);
float average;
bool tooMany;
int scores[MAX_SIZE];
int oneScore;
int id[MAX_SIZE];
int count;
rss.open("studentScore8.txt");
if (rss.fail()){
cout << "error in opening studentScore8.txt" << endl;
}
readStuData(rss, scores, id, count, tooMany);
mean(scores, count);
printGrade(oneScore, average);
printTable(scores, id, count);
rss.close();
return 0;
}
void readStuData(ifstream& rss, int scores[], int id[], int& count,bool& tooMany){
int stuID;
int stuScore;
int i;
for (i = 0; i < MAX_SIZE; ++i) {
rss >> stuID;
rss >> stuScore;
id[i] = stuID;
scores[i] = stuScore;
++count;
}
if (count > MAX_SIZE){
tooMany = true;
}
else {
tooMany = false;
}
}
float mean(int scores[], int count)
{
float sum = 0;
int i;
for (i = 0; i < count; ++i) {
sum = sum + scores[i];
}
return sum / count;
}
void printGrade(int oneScore, float average){
ifstream rss;
rss >> oneScore;
if (((oneScore >= average -10) && (oneScore <= average + 10))) {
cout << "Satisfactory";
}
else if (oneScore == average + 10){
cout << "Satisfactory";
}
else if (oneScore > average + 10){
cout << "Outstanding";
}
else {
cout << "Unsatisfactory";
}
}
void printTable(int scores[], int id[], int count){
int i;
cout << endl;
cout << setw(10) << left << "Student ID" << "|";
cout << setw(6) << right << "Score" << "|" ;
cout << setw(14) << left << "Grade" << endl;
cout << setfill('-') << setw(30) << "" << endl;
for(i = 0; i < MAX_SIZE; ++i){
cout << left << setw(10) << id[i] << "|";
cout << left << " ";
cout << setw(2) << scores[i];
cout << right << " " << "|";
printGrade(scores[i], mean(scores, count));
cout << endl;
}
cout<< setfill('-') << setw(30) << "" << endl;
}

I'm a beginner, trying to write a function that finds the root of an array function

I've been working for a couple hours trying to figure out what I'm doing wrong. All I need to do is find one root from a polynomial represented by an array using Newton's method. The two functions (polyval and polyder) seem to be giving me the right answers, and I feel that the main code is correctly doing Newton's method. I was hoping someone experienced could give me some advice.
#include <iostream>
#include <cmath>
using namespace std;
float polyval(float*, int, float);
void polyder(float*, int, float*);
int main(void) {
int n;
float x=-1,f;
float tol=pow(10,-5);
cout << "Enter polynomial order:" << endl;
cin >> n;
float* p=new float[n+1];
float* dp=new float[n];
cout << "Enter coefficients, starting with the highest power:" << endl;
for (int k=0;k<n+1;k++) {
cin >> p[k];
}
polyder(p,n,dp);
f=polyval(p,n,x);
while (fabs(f)>tol) {
x=x-f/polyval(dp,n,x);
f=polyval(p,n,x);
cout << x << endl;
cout << f << endl;
}
cout << "A real root is at x= " << x << endl;
cout << "To verify: p(" << x << ") = " << polyval(p,n,x) << endl;
return 0;
}
float polyval(float* p, int n, float x) {
float px;
px=0;
for (int k=0;k<n+1;k++) {
px=px+p[k]*pow(x,n-k);
}
return px;
}
void polyder(float* p, int n, float* dp) {
for(int k=0;k<n;k++) {
dp[k] = p[k+1] * (k+1);
}
}
Your call to polyval(dp,n,x) will access beyond the allocated space for dp, which has n entries and not the requred n+1.

C++ Setting the number of array elements within a class

Hi I am working on a class for a weather station that asks a user to input variables and it passes the hours to an array: calculating the values for average, Highs and lows. I got it to work but want to make the array[elements] private. Is it possible to do this?
Here is my code so far. Thank you in advance for any help.
Brian
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures(int[], int);
void DisplayATemperatures( int[], int);
void arrayCalcs(int[], int);
private:
static const int aTemps = 24;
static const int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
int atemps[aTemps];
}
void WeatherStation::GetATemperatures(int atemps[], int aTemps)
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures( int atemps[], int aTemps)
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs(int atemps[], int aTemps)
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures(atemps, aTemps);
alpha.DisplayATemperatures(temps, Temps);
alpha.arrayCalcs(temps,Temps);
cout << "\n";
system("pause");
return 0;
}
1) Is the array atemps[]? If so, it's already private... what's the problem?
2) Why is your array class member static? Don't do that without damned good reason (and as this appears to be a homework assignment, I'm almost certain you don't have a damned good reason).
3) Your constructor has a useless line of code in it -- and that's the only line in the function.
4) Your professor will not accept you naming variables atemps and aTemps -- and if they do overlook it, I would be very concerned for the quality of education you're receiving. It's not that the variable names themselves are a big issue, but rather that you're naming them so similarly, as this is a recipe for a maintenance nightmare if it were to happen in real code.
Edit -- based on our comment-chat, here is my suggestion. I have not tried to compile this and I don't claim this is the best (or even a suggested) way to write your program... my suggestion is limited to leaving the data within your object (in a way that has room for growth beyond this question / discussion).
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures();
void DisplayATemperatures();
void arrayCalcs();
private:
static const int aTemps = 24;
int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
}
void WeatherStation::GetATemperatures()
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures()
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs()
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures();
alpha.DisplayATemperatures();
alpha.arrayCalcs();
cout << "\n";
system("pause");
return 0;
}