Garysully1986
Garysully1986

Reputation: 49

Filling arrays from a text file

I am having a bit of trouble, I am doing an assignment on statistical hypothesis testing. I can do all the calculations on paper but am having trouble with reading from a file to an array.

Here are the numbers I need, They are already contained in the text file input1.txt exactly as below.

14

0.5923 0.58 0.6008 0.6117 0.6295 0.6088 0.6148 0.6369 0.6372 0.6241 0.6034 0.6108 0.591 0.601

109.31 110.13 108.9 108.96 108.86 109.17 109.29 108.62 109.06 108.61 109.83 110.48 111.53 111.02

I want to define the array size to be 14 from the first line then two seperate arrays for the first 14 digits and the second 14. If that makes sense, I need it to be filled from the text file and not inputted by the user.

At the moment I can only get it to read in all the data to end of file. I need it to read each to end of line I think?

Any help would be much appreciated.

Here is what I have so far.

    #include "std_lib_facilities.h"
    #include <cctype>
    #include <iostream>
    #include <fstream>

    using namespace std;

    int main()
     {
int array_size; //I want this to be 14, read from the first line of txt file
double * array1; 
double * array2;
ifstream fin("input1.txt"); //opening an input stream for file

if (fin.is_open())
{
    cout << "File opened" << endl;
    cin >> array_size;
    cout << "N = " << array_size << endl;
    array1 = new double[array_size]; //allocate memory for arrays
    array2 = new double[array_size];
    for (int i = 0; i < array_size; ++i) //fill array1
        cin >> array1[i];
    for (int i = 0; i < array_size; ++i) //fill array2
        cin >> array2[i];

    cout << "Arrays are below" << endl << endl;
        cout << "Additive  ";
    for (int i = 0; i < array_size; ++i)
        cout << array1[i] << ' ';
    cout << endl;
        cout << "Yield  ";
    for (int i = 0; i < array_size; ++i)
        cout << array2[i] << ' ';

}
else
{
    cout << "File could not be opened." << endl;
}

fin.close();


return 0;
    }

Upvotes: 2

Views: 1620

Answers (1)

Roman Sobkuliak
Roman Sobkuliak

Reputation: 56

You want to read from a file, but you use cin, which reads from standard input. Just change cin to name of your opened file stream - fin ;)

Upvotes: 1

Related Questions