Reading a file in C++

My engineering computations teacher gave us an assignment that requires the program to read the text in a text file. The text in the file is a column of numbers. I used the code he gave us and when I ran the code, it just gave back a lot of values scrolling down the screen.

[code]
using namespace std;
#include <iostream>
#include <fstream>


ifstream Infile;
float InData[100];
int i;

int main()
{
Infile.open("data.txt");
i=0;
while(!Infile.eof())
{
Infile>>InData[i];
cout<<InData[i]<<"";
i++;
}
Infile.close();
cout<<"number of data points"<<i<<endl;
system("pause");
return(0);
}
The text in the file is a column of numbers.

If you can read the numbers when you open the file they aren't stored in a format compatible with float. Reading text-based numbers into a float (or double) variable will read garbage values.

Read your data using either a C-style char string or C++ std::string.

Personally I would recommend using C++ std::string. Read as a std::string and then use one of the string class functions to convert to a float.

http://www.cplusplus.com/reference/string/

The C library <cstdlib> have functions to do C-style char string conversions.

http://www.cplusplus.com/reference/cstdlib/
He gave you a (slightly-flawed) code to START from.

Presumably he gave you a TASK to amend that code so that it does some ... engineering calculation ... on.

At the moment it does indeed read in successive numbers: Infile>>InData[i];
and output said numbers: cout<<InData[i]<<"";

All it does of any consequence at the moment is count those numbers: i++; ... which it manages to do wrongly because it used while(!Infile.eof())


So what does your "Engineering Computations" teacher actually ask you to do with those numbers?
He asked us to have the program read the numbers from the text file and calculate mean and standard deviation using the numbers.
Okay, so why don't you give it a try? In the code you posted I see no attempt to actually use the values retrieved from the file, other that the print out.

Do you know how to compute the mean and standard deviation?

Topic archived. No new replies allowed.