Click to See Complete Forum and Search --> : file input


elimin8tor
June 4th, 2002, 10:03 AM
Hi, I want to read some data from a file for example something like this:

3 // number of variables
var1 = 40
var2 = 50
var3 = 70

I only want to read the value of the vars and write them to an array in my program, but I can't find out how to read the data as integers and not as characters :(

Any hint or sample app as it should be easy for the professional would be nice

Philip Nicoletti
June 4th, 2002, 01:15 PM
you can use standard C++ iostream ....


#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
vector<int> array;

ifstream infile("test.txt"); // open input file (it is close automatically)

if (infile) // if opened OK
{
int i,j,n;

infile >> n; // read in number of integers
if (infile.fail())
{
cout << "error reading number of integers" << endl;
return 1;
}

for (i=0; i<n; i++)
{
infile >> j; // read in next integer
if (infile.fail())
{
cout << "error reading integers" << endl;
cout << "read in successfully " << array.size() << " integers" << endl;
return 1;
}
array.push_back(j); // store in the array
}

cout << "values read in ... " << endl;
for (i=0; i<array.size(); ++i)
{
cout << array[i] << endl;
}
}
else
{
cout << "unable to open input file " << endl;
return 1;
}

return 0;
}

elimin8tor
June 4th, 2002, 01:40 PM
thx