0

I am trying to deal with a text file for a while and I searched the forums but unfortunately I do not know how can I do this task. What I want to do is to read some variables from a text file and assign the numbers to different variables. The input format of text file is as follows:

n=1;

m=1;

l= [[1,2,3],
[4,5,6]];

a1= [ [2 2 2]];

a2=[[4,4,4] ];

So as can be seen there are different types of variables. So I want the code assign 1 to n, 1 to g and be able to assign the numerical values corresponding to a1 and a2 as well (it has different length in different time periods). I guess the key is to find the name of variable in each line and if it is n, then assign n to variable n and for example if variable is a1, assign 2 2 2 to a1. In each line, after finding the variable name, I tried to read to numerical values after '=' but I was not successful. Below is what I have tried so far:

std::string line, sub;
ifstream myfile;

//test for reading
std::ifstream file("Input.dat");
std::string name;
while (file >> name) {

    getline(file, name);
    cout <<":"<< name << endl;
}
/*while (file >> name) {
    int a;
    int b,c;

    file >> a >> b;
std::cout << name << ' ' << a * b << '\n';
}*/

//end of test

file.close();
//reading from the .datfile
    myfile.open("Input.dat");
while (std::getline(myfile, line))
{
    std::stringstream  linestream(line);
    if (line.find("n = ") == string::npos)
        //      

        continue;
    istringstream ss(line);// copies current line to ss
    double x, y, z;
    ss >> x >> y >> z;
    if (!ss)
  • 1
    "I was not succesful" isnt helpful at all at explaining what is the problem. Also you didnt ask a question. You should use a debugger to find out what your code does, how and why it differs from what you expect – 463035818_is_not_an_ai Jul 06 '17 at 09:49
  • 1
    This question appears too broad to fit here, but maybe this can get you started: https://stackoverflow.com/q/380455/1025391 – moooeeeep Jul 06 '17 at 10:01
  • First of all your input text **Not Easy To Parse** . Secondly for this type of task you can use **std::stringstream** and a container to **stack** your numbers. Also you can use **Regular Expression** but that become a little bit hard – Shakiba Moshiri Jul 06 '17 at 14:12
  • I guess there might be some ways for writing this code, one way would that if we try to read a character twice, I mean we read a character once in integer and once in char format. Is there any solution for this? – questionnaire12 Jul 07 '17 at 18:33

0 Answers0