Find answers, ask questions, and connect with our <br>community around the world.

Home Forums CPP scientific computing discussion Lesson 16: Reading Data file

  • Lesson 16: Reading Data file

    Posted by Himanshu on March 11, 2024 at 2:00 am

    Hello Professor,

    I have a question regarding reading data. I wanted to know how can we access data from each row and column, for the example shown in the lecture; by

    read_data >> x_coords[i] >> y_coords{i};

    does it mean that the columns are selected accordingly, i.e, the first column representing x_coords and second column representing y_coords.

    I am also having trouble reading the Parameter.txt file. I have added my code and the output below:

    //This code is used to Read data from Parameter.txt

    #include<iostream>

    #include<cassert>

    #include<fstream>

    #include<string>

    int main(int argc, char *argv[])

    {

    double value[8];

    std::string parameter[8];

    // Open the file for Reading

    std::ifstream read_data(“Parameters.txt”);

    // Asserting whether file is open

    assert(read_data.is_open());

    //Reading from Files

    for(int i = 0; i < 8; i++){

    for(int j = 0; j < 8; j++){

    read_data >> parameter[i] >> value[j];

    }

    }

    read_data.close();

    for(int a = 0; a < 8; a++){

    std::cout << “Value: ” << value[a] << std::endl;

    }

    return 0;

    }

    Nishant replied 2 weeks ago 2 Members · 1 Reply
  • 1 Reply
  • Nishant

    Member
    April 6, 2024 at 5:56 am

    Hi Himanshu.
    I apologize for the prolonged delay in my reply as my laptop was under repair due to some hardware glitch. When you are reading data from a Parameter.txt file, we usually read the data one entry at a time, line by line. Therefore, if your data is in the form of a table in that you case your code should be written in a way that the data is being read in a row-wise fashion, meaning you read the data from all the columns in a row and then move on to the next row. This is effectively what you do when you write nested for loops,

    for(int i=0; i<num_rows; i++)
    for(int j=0; j<num_cols; j++)
    {
    // Read data from all the cols of the i^{th} row
    }

    I hope the understanding will help you to modify and debug your code.

    Regards,
    Nishant

Log in to reply.

error: Content is protected !!