I am a bit confused on what the code for reading in an array from a file is. I keep getting error messages. Can anyone help by giving examples on the proper way to do it? Is it also possible to use a for loop?
Very bottom is where i am confused, I open the file globally.
#include <iostream>
#include <fstream>
usingnamespace std;
void readdata(int [], int &);
constint SIZE = 100;
ifstream infile;
int main()
{
int array[SIZE];
int n = 0;
readdata(array, n);
cout << array[SIZE] << " and " << n << endl;
system("PAUSE");
return 0;
}
//Function readdata():
//Input:
// array: an array of integers
// n: the number of elements in the array.
//Process:
// read in elements from a file into array
// finds the sum of the elements
//Output:
// returns the array to the calling function
// returns the number of elements to the calling function
void readdata(int arr[], int n)
{
infile.open("file1.txt");
int i = 0;
fin >> arr;
while(fin) {
fin >> arr;
n++;
i++;
}
return;
}
Close the stream when you are done infile.close();
1 2 3 4 5
while(fin) {
fin >> arr[i];
n++;
i++;
}
If you do fin >> arr;, you will just keep overwriting the very first element in the array. Do fin >> arr[i];
But you have to be careful. Your array has a size of 100. What happens if there are more than 100 characters in the file and you keep reading them into the array? You'll go out of bounds, and whoops, segmentation fault (probably, if you're lucky, if you're unlucky you'll overwrite some other memory location and mess something up).
Have a break condition if the number of characters you have read reaches 100.
Using a for loop will work great
1 2 3 4 5
for (int i = 0; i < 100; i++)
{
fin >> arr[i];
n++;
}
In the above for-loop, you will never read more than 100 characters, and you won't have an out-of-bounds problem.
I fixed the while loop but i keep getting the message fin undeclared, so i used the for loop and same message but the program works when I changed fin to infile in the for loop.
But now that i have done this my output is not what it should be, this is what i get:
These are the elements in the array: 2686792
The number of elements in the array is 100
Press any key to continue . . .
When i should be getting:
These are the elements in the array: 6 66 0 -4 0 4 31 22 0 49
The number of elements in the array is 10
Press any key to continue . . .