I'm trying to create an array, write array to the file and than display it. It seems to be working but i get just part of the output (first 3 elements) or i get values over boundaries.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int arr[20];
int i;
for (i = 0; i < 5; i++)
{
cout << "Enter the value to the array: " << endl;
cin >> arr[i];
}
ofstream fl("numbers.txt");
if (!fl)
{
cout << "file could not be open for writing ! " <<endl;
}
for (i = 0; i < arr[i]; i++)
{
fl<<arr[i]<<endl;
}
fl.close();
ifstream file("numbers.txt");
if(!file)
{
cout << "Error reading from file ! " << endl;
}
while (!file.eof())
{
std::string inp;
getline(file,inp);
cout << inp << endl;
}
file.close();
return 0;
}
It is wrong beacuse it comapres with the content of the array ,it does not check the size of array .
Try this:
[EDITED] I would initialize the array with 0 like this: int arr[20] = {0}; In this case you can use for example:
The terminating condition in the
for
loop is incorrect:If the user enters the following 5
int
s:the
for
loop will terminate at the secondint
, the0
, as1 < 0
(which is whati<arr[i]
would equate to) isfalse
. The code has the potential to access beyond the bounds of the array, for input:the
for
loop will iterate beyond the first 5 elements and start processing unitialised values in the arrayarr
as it has not been initialised:which could result in out of bounds access on the array if the elements in
arr
happen to always be greater thani
.A simple fix:
Other points:
always check the result of I/O operations to ensure variables contain valid values:
the
for
loop must store the number ofint
s read into thearr
, so the remainder of the code only processes values provided by the user. An alternative to using an array, with a fixed size, and a variable to indicate the number of populated elements is to use astd::vector<int>
that would contain only validint
s (and can be queried for itssize()
or iterated using iterators).while (!file.eof())
is not correct as the end of file flag will set only once a read attempted to read beyond the end of the file. Check the result of I/O operations immediately:its like hmjd said
looks wrong
it should look like this