-1

I'm a beginner and maybe the solution here is easier that I think it is, but I have spend a lot of time trying to fix this problem. The main goal is to create a dynamic array from a file.

I have this code:

#include <iostream>
#include <fstream> 

using namespace std;

void out(int *arr, int siz){
    for (int i = 0; i < siz; i++) {
        cout << arr [i] << " ";
        if((i + 1) % 5 == 0){
            cout << endl;
        }        
    }
}

int main(){
    int *arr;
    int i = 1;
    int len = 0;

    ifstream fin;
    fin.open("input.txt");
    int s; 
    fin >> s;     
    arr = new int[s];

    while(!fin.eof()){ 
        fin >> arr[i]; 
        len++;       
        i++;
    }
    fin.close(); 

    out(arr, len); 
    delete[] arr;

    return 0;
}

And file looks like this:

11
84
65
80
62
98
2
4
75
69

But the output looks like this:

0 84 65 80 62 
98 2 4 75 69 

The problem is that it counts first element as 0, instead of 11.

Expected output:
    11 84 65 80 62 
    98 2 4 75 69 

I have tried changing parts of the code, but I still didn't manage to find the proper solution. Do you have any ideas what I'm doing wrong?

2 Answers2

1

You can do something like this:

#include <iostream>
#include <fstream> 
#include <vector>

void out(const std::vector<int>& arr) {
    for (size_t i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << " ";
        if ((i + 1) % 5 == 0) {
            std::cout << std::endl;
        }
    }
}

int main() {
    std::vector<int> arr;

    std::ifstream fin("input.txt");

    for (int data; fin >> data;)
        arr.push_back(data);

    fin.close();

    out(arr);
}

I changed the C-style array to an std::vector and changed the loop condition (both Remy Lebeau and I posted comments detailing why this is correct). This in turn made your "off by one" indexing error go away (the cause of the initial 0).

Frodyne
  • 3,547
  • 6
  • 16
0

use a vector;

#include <vector>

int main(){

    vector<int> arr;

    ifstream fin;
    fin.open("input.txt");
    int s; 
    

    while(!fin.eof()){
        int temp; 
        fin >> temp;
        arr.push_back(temp);
    }
    fin.close(); 

    for(auto v:arr) cout<<v<<"  ";
    cout<<endl;
    arr.clear();

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
satyam
  • 21
  • 4
  • 1
    [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/) – Remy Lebeau May 30 '22 at 10:39