I had my code working properly, but once I added my last array, it goes through the compile and then errors out....and I'm not quite sure why....

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
using namespace std;

int main()
{
	double num[100], sum, count, newnum[100];
	int j,i;

	ifstream Input;

	Input.open("InputNumbers.txt");

	if (Input.fail())
	{
		cout << "Can't Open Input File!" << endl;
		exit(1);
	}

	count =0;
	sum=0;
	while (!Input.eof())
	{
		for (j=0;j<=7;j++)
		{
			Input >> num[j];
			cout << num[j] << " ";
			count++;
			sum+=num[j];
		}
	}


	cout << endl;
	cout << num[0] << " " << num[1] << " " << num[2] << " ";
	cout << endl;
	cout << "Count = " << count << endl;
	cout << "Sum = " << sum << endl;

	double average = sum / count;
	cout << "Average = " << average << endl;

	j=0;
	for(i=0;i<=(j+1);i++)
	{
		newnum[i]= pow((num[j]-average),2);
		j++;
	}

	return 0;
}

Edited 6 Years Ago by PDB1982: n/a

I figured out the reason it wasn't compiling correctly, and it was because I was trying to increase j while inside the loop....take it out, and it works perfectly....

You still have the for loop within the while loop which I think someone had pointed out already. What happens when your file has 9 values in it? You don't need it anyway, just increment j within that while loop.

You still have the for loop within the while loop which I think someone had pointed out already. What happens when your file has 9 values in it? You don't need it anyway, just increment j within that while loop.

Well, that's what I wasn't sure of at first....I wanted to implement some code that would accept an unknown amount of data, which was why it was placed within the while loop (which I hoped would search for the data until the end of the file), but I wasn't sure how to relate that to the actual loop structure.

In reality you can make your loop something like while(Input >> num[j]) and increment j within the while loop. If you know you have a constraint of 100 items and no more you can incorporate that into the while as while(j<100 && Input>>num[j]) just make sure j is initialized.

In reality you can make your loop something like while(Input >> num[j]) and increment j within the while loop. If you know you have a constraint of 100 items and no more you can incorporate that into the while as while(j<100 && Input>>num[j]) just make sure j is initialized.

Awesome! Thanks for your help! I will give it a whirl!

This question has already been answered. Start a new discussion instead.