-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
  • 1
    Your loop is not good: stackoverflow.com/q/5605125/11829247 Commented May 30, 2022 at 10:35
  • The first element in your array is 0 because i is initialized to 1 (arrays in C++ starts at 0) Commented May 30, 2022 at 10:36

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.