I'm new to coding and recently took up a C++ course to help with some computer modelling that I'm doing as part of my PHD. Unfortunately, the other people on the course are a little bit more experienced and I'm struggling to keep up!
One exercise that's been vexing me is one where I have to load a text file that is a list of integers on seperate lines and then find the average of these integers.
I've successfully loaded the text file, but I'm struggling to work out an average. I know this may seem simple but I am a complete begginner!
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <iostream> /* cin and cout functions */
#include <cmath> /*for power function etc.. */
#include <string> /*to let us use strings as inputs */
#include <sstream> /*allows conversion of strings to floats */
#include <fstream> /*has all the file input functions */
usingnamespace std; /*saves some typing*/
int main () {
string line;
int number;
ifstream myfile ("Numberlist.txt"); //Open up file
if (myfile.is_open())//Check to see if file is open
{
while ( getline (myfile,line) )
{
stringstream ss; //Convert string to integer
ss<<line;
ss>>number;
cout << number << endl;//Output integers - I put this step in just to make sure the file was actually loading
}
myfile.close();
}
else cout << "Unable to open file"; //Check to see if file is open
system("Pause");
return 0;
}
I tried to put each line as an integer in an array but failed. I've looked at quite a few pre-existing faqs/tutorials which has got me this far but no further.
int main () {
string line;
int number;
std::vector<int> lstnumbers;
ifstream myfile ("Numberlist.txt"); //Open up file
if (myfile.is_open())//Check to see if file is open
{
while ( getline (myfile,line) )
{
stringstream ss; //Convert string to integer
ss<<line;
ss>>number;
cout << number << endl;//Output integers - I put this step in just to make sure the file was actually loading
lstnumbers.push_back(number);
}
myfile.close();
}
// here loop through the vector keeping a runnning
// sum total then divide by the size of the vector (cast the size to a double
// before the division).
You should look at vectors. There is a great reference on this site. The nice thing about vectors is they grow in size as you add more items into your vector.
So, in your "while" loop, add each number to your vector. When there is no more input, loop through your vector and do your calculations.
you won't really be needing getline since you are just fetching numbers, and numbers doesn't have spaces
you can do store the values in an array and compute it later using something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constint MAX_SIZE = 100;
int nVar[MAX_SIZE];
if ( myfile.is_open() ) {
int i = 0;
while ( myfile >> nVar[i] ) {
i++;
}
// Compute and print the average
} elsereturn 0;
EDIT: forget it, use vector like the guys above say for efficiency