C++ file writing/reading

2019-08-16 01:53发布

问题:

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;
}

回答1:

its like hmjd said

for(i=0;i<arr[i];i++)

looks wrong

it should look like this

int size;
size=sizeof(your array);

for(i=0;i<size;i++)


回答2:

The terminating condition in the for loop is incorrect:

for(i=0;i<arr[i];i++)

If the user enters the following 5 ints:

1 0 4 5 6

the for loop will terminate at the second int, the 0, as 1 < 0 (which is what i<arr[i] would equate to) is false. The code has the potential to access beyond the bounds of the array, for input:

10 11 12 13 14

the for loop will iterate beyond the first 5 elements and start processing unitialised values in the array arr as it has not been initialised:

int arr[20];

which could result in out of bounds access on the array if the elements in arr happen to always be greater than i.

A simple fix:

for(i=0;i<5;i++)

Other points:

  • always check the result of I/O operations to ensure variables contain valid values:

    if (!(cin >> arr[i]))
    {
        // Failed to read an int.
        break;
    }
    

the for loop must store the number of ints read into the arr, 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 a std::vector<int> that would contain only valid ints (and can be queried for its size() 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:

    while (std::getline(file, inp))
    {
    }
    


回答3:

Try this:

//for(i=0;i<arr[i];i++)
for(i=0;i<5;i++)

[EDITED] I would initialize the array with 0 like this: int arr[20] = {0}; In this case you can use for example:

while ((arr[i] != 0 || i < sizeof(arr)) 


回答4:

i<array[i]

It is wrong beacuse it comapres with the content of the array ,it does not check the size of array .