Click to See Complete Forum and Search --> : Input from file & FOR loop
evangogh
July 9th, 2002, 04:28 PM
I am a newbie working on a problem that will perform various mathematical functions. My problem is I would like to know how to read in values from a file using FOR loops. I need to read in the number of values followed by the sequence of values. (I've been playing around with this for over a week and just need some help to get the ball rolling.) Thanks in advance!
cup
July 9th, 2002, 05:01 PM
Could you give an example of what your datafile looks like.
jfaust
July 9th, 2002, 05:04 PM
Roughly (may be problems, but here's an idea)
#include <fstream>
using namespace std;
void processFile(string filename)
{
ifstream f(filename);
vector<double> values;
int count;
f >> count;
for( int i = 0; i < count; ++i )
{
double val;
f >> val;
values.push_back(val);
}
}
Jeff
zdf
July 9th, 2002, 05:49 PM
Just an idea
#include <fstream>
using namespace std;
int main()
{
ifstream is("input");
if ( ! is )
return 1; // error opening
while ( is.good() )
{
int count;
for ( is >> count; is.good() && count; count-- )
{
double d;
is >> d;
// do something creative here
}
if ( count )
return 2; // error too few values
}
return 0;
}
The input file may look like this:
4 1.2 3.4 5.6 6.7
2
1.2
1.3
Regards,
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.