Build array of values from data file.

Hello,

I am new to this forum; please forgive me if this question has been previously posted. I did scan the site, however, some of the answers were over my head after only 8 chapters of C++

I have a program I need to write to do many things:
Calculate average
Calculate min/max
Calculate standard deviation
Determine and write a quartile summary

Although challenging at first I understand how to set up and call the functions to achieve the above requirements.

However, I do I write the data into my array/
The array size is no larger than 500 (exact size unknown)

I do understand:

How to open a file: ifstream input("myfile");

How to declare the array and the size
const int num_elements = 500;
int array[num_elements];

How do I get the file information into the array?

I suspect a suspect a for loop so that I can step through the elements.

any advice?
Last edited on
for(int i = 0; i < 500 && input << array[i]; i++);would be one way (intentionally not very readable. Just so that you can think about it). see http://www.cplusplus.com/doc/tutorial/files/
I have attempted to use the above for loop, declared the input as an int so that it could compile but got some crazy results.

I figured I would write a smaller array (10 pieces of data: "test scores") so that I could output the contents to the output consoles easily.

Here is what I have coded; It compiles, however, not with the expected results.
I have researched the code, referenced my book, but cannot find my error.

Can anyone help me isolate the problem with this code.
Looking at my C++ book it seems correct and I have tried several different approaches.
The test data in input:
82
77
90
89
63
71
75
86
45
78

I am expecting these numbers to be displayed, however, I get a negative value:

- 539042340
Although I laughed... it's not very funny LOL.

Here is the code:

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

int main()
{

const int SIZE = 10; //Size declaration of array
int scores[SIZE]; //Array declaration
int count; //Loop counter variable
ifstream inputFile; //Input file stream object


inputFile.open("myTestData.txt"); //Opening the file



//Read numbers from file into the array
for(count = 0; count < SIZE; count++);
inputFile >> scores[count];

//Close the file
inputFile.close();

//Display the numbers in the array
cout << "The numbers are: \n";
for(count = 0; count < SIZE; count++);
cout << scores[count] << "";
cout << endl;


system("pause");
return 0;
}
Any input would be greatly appreciated.

Kindest regards,

Joseph
I have since removed the ; after my for loops.

I do get 10 numbers now, however, not the numbers from my text file

I get output such as:

2686672
2
2686916
197365570
-802308932
-2

Last edited on
There's nothing wrong with the code (except for the ;s).
There may be something wrong with the file however.
Check if it is int the right directory. Also, any text going before the numbers would cause an error.
add a line if(!inputFile) cout << "there's something wrong with the file!\n";
Your awesome!!
the new output is "there's something wrong with the file!

and then the same as above.

Thanks for helping me isolate things.

I should have know to validate the file first that's standard protocol.
The array size I have to declare is 500 elements, however, the text file is only 384 integers.
I am getting invalid output from my code.

Do can you point me to something else to read, or, give some advice. Perhaps both, point out error and suggest what I may want to read up on again?

Kindest regards and thanks for everything.

Here is my code; I hope you find it to be easy to read.

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

int main()
{

const int SIZE = 500; //Size declaration of array
int scores[SIZE]; //Array declaration
int count; //Loop counter variable
ifstream inputFile; //Input file stream object


inputFile.open("myTestData.txt"); //Opening the file
if(!inputFile) cout << "there's something wrong with the file!\n"; //Throw exception



//Read numbers from file into the array
for(count = 0; count < SIZE && inputFile >> scores[SIZE]; count++)
inputFile >> scores[count];

//Close the file
inputFile.close();

//Display the numbers in the array
cout << "The numbers are: \n";
for(count = 0; count < SIZE; count++)
{
cout << scores[count] << "";
cout << endl;
}

system("pause");
return 0;
}
1
2
for(count = 0; count < SIZE && inputFile >> scores[SIZE]; count++)
inputFile >> scores[count];
That's not quite right. inputFile >> scores[SIZE] rads an int to a non-existent element of scores array.
you could either for(count = 0; count < SIZE; count++) inputFile >> scores;, or for(count = 0; count < SIZE && inputFile >> scores[count]; count++); which is better as it will stop looping when input fails. Note that when that happens, you have to save the number of integers read, so that you don't try to print 500 when there were only 300.
OH!!! I see! I goofed when I wrote the part of the for loop where I wrote inputFile >> scores[SIZE] because SIZE is referencing the number of elements (the int) in the array; Not a subscript in the array in which we can store an element of data.

Also, I have to perform other calculations on the data that are trivial. Min/Max, Avg, basic stuff for college students.

Are you suggesting that I save the array in the program itself and then continue?

That would involve counting the elements in my scores[array] and then creating a new array with the exact number of elements to be written into another array, am I understanding you correctly?

Once this is done, continue processing that data with the min/max functions correct?
Right. Read it into an array (you already do that..). There is no need to create a new array of correct size. Few hundred bytes is not much. After you're done with the input, save 'count' to a variable like 'scores_length' and in for loops of your algorithms, write 'count < scores_lentght' instead of 'count < SIZE' .
Thanks a lot Hamsterman, I am very greatful for you.

In addtion to school I work 47.5 hours per week. Unless I take of work I cannot make it to my professor for help; and, although they do reply to email, it isn't nearly as prompt. Thus leaving many hours of waiting.

I'm at work now and must go, but, thank you very very much.


Kindest regards,
Joseph
I have successfully counted the number of elements in the array once the text file is read into the array. I sent the output as number of elements to the console to verify that I coded that part correctly.

I attempted to assign the 'score_length' size to the array but came up with errors. It will compile but the output is not the same as what is in the txt file.

When I omit the step in which I attempt to index thru the score variable everything works fine.

Here is where things are so far. I have attempted several variations of this code but have not
successfully implemented any of them.



//Opening file and validate file has open. Throw exception if necessary.
inputFile.open("myTestData.txt");
if(!inputFile) cout << "Problems with file!\n";


//Read numbers from file into the array.
for(count = 0; count < SIZE && inputFile >> score[count]; count++)
inputFile >> score[count];

//Variable to determine size of array.
int score_length;

//Loop to assign length of data to scores_length.
for(score_length = 0; score_length < count; count++)
{
score_length += count; //Accumulator for score elements
cout << "You have processed: \n";
} cout << (score_length - 1) << " test scores\n"; //Elements minus null


//Index variable to step through array and display elements.
int index;

//Display elements to output console
cout << "The numbers are: \n";
for(index = 0; index < score_length; index++)
{
cout << score[index] << "";
cout << endl;
}

//Closing after getting data.
inputFile.close();

My logic is this, please correct me if I am wrong.

Declare the array of 500 (because that is what the professor requires)

Read the text file into the array(this has been done successfully)

Step through the array and display the elements(also done successfully)

Save the elements in the array to a variable (done successfully - 'score_length')
*** I did output the 'score_length' to the output console too to verify I coded correctly)

Index through the loop using the array "score" with an actual size of [score_length]
and output to screen.

The results are not the correct when I index through score[score_length]. I am using 10 integers I created to test my code before continuing. I do get 10 numbers, but, not the 10 I entered into the text file



no no no.
1
2
for(count = 0; count < SIZE && inputFile >> score[count]; count++)
inputFile >> score[count];
is wrong. Here's what happens:
1. count = 0;
2. check if 0 < SIZE
3. read an int form inputFile to score[0]
4. check if 2 and 3 are both successful
5. read an int form inputFile to score[0] (again!)
6. count++;

What happens here, is that only every other element is stored in the array. (I'll explain why you get correct result later)

I already gave you the right code: either for(count = 0; count < SIZE && inputFile >> scores[count]; count++);//yes. here is a ';'. Everything that needed to be done already happened.
or for(count = 0; count < SIZE; count++) if( !(inputFile >> scores) ) break;.

Now, the counting:
1
2
3
int score_length; 
for(score_length = 0; score_length < count; count++)
    score_length += count;
How did you think of that? All you had to do is score_length = count. Let's see why this works. Note that due to previous errors, count is N/2 (where N is the number of elements in file).
1. score_length = 0, so it is < count.
2. score_length += count, so it is == count.
3. count ++ so score_length < count once again.
4. score_length += count, so it is == count*2 == N (the correct size)
5. count ++. now count = N/2+2 and score_length = N so score_length < count returns false and the loop ends.
Don't say using namespace std; and use count as an identifier in the same .cpp file. Preferably, just don't say using namespace std; ever, as it pollutes the global namespace with a bunch of names you don't need and can cause clashes. std::count() is a function in the standard library.
When I wrote:
1
2
3
int score_length; 
for(score_length = 0; score_length < count; count++)
    score_length += count;


I wanted to display what was read from the text file into the array.
However, after reading your reply concluded what is below and it works.
1
2
3
cout << "Here are your numbers: \n";    
    for(count = 0; count < score_length; count++)
     cout <<" "<< score[count];



I do see that the ' ; ' at the end of my for loop made the difference between getting N (when I did include the ' ; ' ) and N/2 (when I did not use the ' ; ') Why is does that happen?

When I wrote the " for loop" what was going through my head (and obviously wrong) was this:


1
2
for(count = 0; count < size  &&  inputFile[count]; count++) //Initalize; test; update
   inputFile >> score[count];  //Get data while data is available. 


Which gave me the N/2 results.

Why does it read every other number when you do not have the ' ; ' at the end of the loop?

Moving on to the next part of my program.

Thank you for your patience, time, and consideration.

Kindest regards,
Joseph
that's because 'test' already does the reading, so it happens twice.
Topic archived. No new replies allowed.