-
Simple File I/O problem
The problem is simple enough...
Here the "read" part of my program..
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
int array[100];
ifstream file ("in.in");
if(file.is_open())
{
int x=0;
while(!file.eof())
{
file>>array[x];
x++;
cout<<*array<<endl;
}
file.close();
cout<<*array;
}
else
cout<<"Unable to open file!"<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Well my problem is how to transfer all of the data to my array, what I'm doing really is just copying the first line. Thanks in advance.
-
well, the problem is (mostly) with your output... read on:
Code:
#include <iostream>
#include <fstream>
using namespace std;
/*
* don't worry about declaring the variables if you don't intend to use them.
*/
int main()
{
int array[100];
fstream file ("test.dat",std::ios::in);
/*
* I'd do something like this so that you don't have to wrap all
* your code in an if statement
*/
if(!file.is_open())
{
std::cout<<"Unable to open file!"<<std::endl;
exit(1);
}
int x=0;
/*
* you should generally use a read to control a loop - check the FAQ
* to find out why
*/
while(file>>array[x])
{
/*
* your main problem was here - you were outputting the pointer
* to the first element of the array over and over again.
* instead of
* cout<<*array<<endl;
* you should have
*/
cout<<array[x]<<endl;
x++;
}
file.close();
/*
* you had an output here that would have tried accessing uninitialized
* data if I had left it in and modified it to work.
*/
/*
* avoid using system() whenever you can - it makes your code non-
* portable, and much worse, opens up a huge security vulnerability
*/
std::cout<<"Press ENTER to Continue..."<<std::endl;
std::cin.get();
/*
* also, avoid using macros if possible. Return '0' instead of
* EXIT_SUCCESS
*/
return 0;
}
-
Thanks that did the trick....
Sorry about the simple mistakes I'm kinda new to FILE I/O and some of the things there were automatically put in since I was using Dev-C++ 4.9.9.2
Thanks again :)
-
As long as we're cleaning up the code a little, I'd add one more check. This:
Code:
while(file>>array[x])
Should maybe be this:
Code:
while(x < 100 && file>>array[x])
This ensures that we don't accidentally try to read in too much data (more than the array can handle).