SAMAN MOKHTARI
SAMAN MOKHTARI

Reputation: 13

Store data from the file into array

I have a file which contain these data :

6
1231234213 12
2312354234 23
3254132515 43

I want to store all these data into an array :

int main() {
    ifstream infile("data.txt");
    ofstream outfile("final.txt");
    int sn = 0;
        infile >> sn;
    int* arr;
    arr = new int[sn];
    for (int i = 0; i < sn; i++)
    {
        infile >> arr[i];
    }
    for (int i = 0; i < sn; i++)
    {
        cout << arr[i] << endl;
    }
}

but I'm getting this instead of those data :

1231234213
12
2147483647
-842150451
-842150451
-842150451 

Upvotes: 0

Views: 49

Answers (1)

Chris
Chris

Reputation: 36451

When testing with an array of long long int your problem disappears:

int main() {
    std::ifstream infile("data.txt");
    int n = 0;
    
    infile >> n;

    long long int *arr = new long long int[n];

    for (int i = 0; i < n; i++) {
        infile >> arr[i];
    }

    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << std::endl;
    }

    return 0;
}

Output:

1231234213
12
2312354234
23
3254132515
43

You might make things easier on yourself by using a std::vector.

int main() {
    std::ifstream infile("data.txt");
    int n = 0;
    
    infile >> n;

    std::vector<long long int> vec(n);

    for (auto &i : vec) {
        infile >> i;
    }

    for (auto i : vec) {
        std::cout << i << std::endl;
    }

    return 0;
}

If we use just int, we can check if the read succeeded. How you choose to handle that error is up to you and the requirements of your program.

E.g.

    for (auto &i : vec) {
        if (infile >> i) continue;
        std::cerr << "A problem occurred." << std::endl;
        i = -2;
    }

Now output is:

A problem occurred.
A problem occurred.
A problem occurred.
A problem occurred.
1231234213
12
-2
-2
-2
-2

Upvotes: 2

Related Questions