+ Reply to Thread
Results 1 to 2 of 2

Thread: Read floating point numbers

  1. #1

    Read floating point numbers

    I want to read floating point numbers from a file into an allocated 2D array.

    In my .txt file the elements of a row are separated by a tab space each and each row starts on a new line.

    So can I increase the size of my array based on the no. of elements (rows and columns) present in the file? If so, please suggest a way to do it.

  2. #2
    Consider using a std::vector than arrays, which automatically resizes. In C++, this is strongly preferred to using a raw array, since it's safer and hides the resource management.

    In fact, using a std::vector in conjunction with the stream libraries, it's very easy to read a file of tab-separated floating-point values:
    ifstream input("my-file.txt");
    vector<float> myValues;
    for (float f; input >> f; )
    Or, alternatively:
    ifstream input("my-file.txt");
    vector<float> myValues;
    However, the above code will read a 1D array of floats, rather than the 2D array you wanted. To read a 2D array, one option is to read one line of the file at a time, then use a modification of the above code to break that line into individual floats. For example:
    ifstream input("my-file.txt");
    vector< vector<float> > myValues;
    for (string line; getline(input, line); ) {
        stringstream lineStream(line);
        vector<float> thisLine;

+ Reply to Thread

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts