0

Okay so I have a textfile with only 2 lines of doubles that are comma separated. This will always be the case. Each line will have to go into its own separate array of type double where I will later have to use a linear search to find one array in the other. example of the textfile:

2.5,6.7,3.4,7,6.7,6,4,5,83.6
6.4,7,8,5.3,9,76

So far I have managed to extract the first line, remove the delimiter and convert it from a string to type double BUT I am having difficulty putting it into an array. I have tried using while loops, for loops (sometimes nested) but they all do not work. I know there is meant to be a simple solution but I can't seem to grasp it or the concept of arrays.

The furthest I am able to code (without messing up) is to simply display it. but I need it in an array. My code follows. Thank you in advance.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    if (inputfile.good())
    {
        string line;
        string num;
        getline(inputfile,line);
        values= slime;
        string stream ss(values);
        while (getline (ss,num ,','))
        {
            cout<<stod(num)<<" ";
            //HOW DO I PUT THIS INTO THE ARRAY INSTEAD PLEASE??
        }
    }

    inputfile.close();
    return 0;
}
yaodav
  • 1,126
  • 12
  • 34

1 Answers1

0

few things - one try not to use using namespace std second - you check inputfile.good() only relevant after reading third - you need an index to run over the array so I added the I that increment with the loop, But I didn't check if it counts more then thy array length so if it relevet add a check for that to.

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

int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    string line;
    string num;
    getline(inputfile,line);
    values= slime;
    string stream ss(values);
    int i=0;
    while (getline (ss,num ,','),)
    {
        cout<<stod(num)<<" ";
        array[i] = stod(num);
        ++i;
    }
    inputfile.close();
    return 0;
}
yaodav
  • 1,126
  • 12
  • 34
  • Thank you so much Yaodav! This definitely helped and I can now proceed with the code. Really appreciate it. –  May 31 '20 at 09:50