0

So in this code, I'm trying to append the smallest number in an array into the file. But whenever I do, It appends 0 and not the smallest number. I had read the numbers into the array from a file, and trying to append the smallest number.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int pcount = 0;
    ifstream inFile;
    inFile.open("numbers.txt");
    int i;
    int myArray[i];

    while (!inFile.eof()) {
        inFile >> myArray[i];
        pcount++;
    }
    inFile.close();
    cout << pcount << endl;

    int temp = myArray[0];

    for (int i = 0; i < pcount; i++) {
        if (temp > myArray[i]) {
            temp = myArray[i];
        }
    }
    inFile.close();

    ofstream outFile;
    outFile.open("numbers.txt");

    cout << "Appended lowest integer into file." << endl;
    outFile << temp;
}
drescherjm
  • 8,907
  • 5
  • 42
  • 60
  • There is an error: you declare `int i` and then `int myArray[i]`. And moreover, you are appending the gratest number, not the smallest. – Eddymage Mar 18 '21 at 17:39

1 Answers1

3
    int i;
    int myArray[i];

is bad because

  • i is used without being initialized
  • VLA (Variable-Length Array) like this is not in the standard C++

You should use std::vector if you want to use array with variable number of elements.

In this case, you won't need array and should just keep track the minimum number while reading the file.

Also note that your usage of while(!inFile.eof()) is wrong.

Try this:

#include <iostream>
#include <fstream>
using namespace std;




int main()
{
    int pcount = 0;
    ifstream inFile;
    inFile.open("numbers.txt");
    int minimum = 0;
    int num;
    
    while(inFile>>num)
    {
        if (pcount == 0 || minimum > num) minimum = num;
        pcount++;
    }
    inFile.close();
    cout<<pcount<<endl;
    
    ofstream outFile;
    outFile.open("numbers.txt");
    
    cout<<"Appended lowest integer into file."<<endl;
    outFile<<minimum;
    
    
    
}

If you want to hold all numbers read on the memory, try this:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;




int main()
{
    int pcount = 0;
    ifstream inFile;
    inFile.open("numbers.txt");
    int i;
    vector<int> myArray;
    
    while(inFile>>i)
    {
        myArray.push_back(i);
        pcount++;
    }
    inFile.close();
    cout<<pcount<<endl;
    
    
    
    int temp = myArray[0];
    
    for(int i = 0; i < pcount; i++)
    {
        if(temp>myArray[i]){
        temp = myArray[i];
        }
    }
    
    ofstream outFile;
    outFile.open("numbers.txt");
    
    cout<<"Appended lowest integer into file."<<endl;
    outFile<<temp;
    
    
    
}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58