|
-
June 4th, 2002, 10:03 AM
#1
file input
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
-
June 4th, 2002, 01:15 PM
#2
you can use standard C++ iostream ....
Code:
#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;
}
-
June 4th, 2002, 01:40 PM
#3
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|