Thread: read float array from file

  1. #1
    Unregistered
    Guest

    Unhappy read float array from file

    The problem is I have text file for example
    2.7 5.0 6.1
    1.5 7.2 4.8
    3.7 8.9 7.0

    and i need to convert this to two-dimensional float array

    how i can read this data and convert it to array.

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    If the size is fixed, it's really easy

    Just a nested loop.

    Code:
    #include <fstream>
    #include <iostream>
    
    const int numRows=3;
    const int numCols=3;
    
    int main() {
    	std::ifstream in("data.txt");
    	float tiles[numRows][numCols];
    
    	for (int i = 0; i < numRows; i++) {
    		for (int j = 0; j < numCols; j++) {
    			in >> tiles[i][j];
    			std::cout << tiles[i][j] << ' ';
    		}
    		std::cout << '\n';
    	}
    
    	return 0;
    }
    If it's not a fixed size, the problem with bigger distraction will be allocating the 2d array.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Unregistered
    Guest
    Thanks but yes the size is not fixed

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Promblem with code
    By watchdogger in forum C Programming
    Replies: 18
    Last Post: 01-31-2009, 06:36 PM
  2. Read file into array
    By neobarn in forum C Programming
    Replies: 6
    Last Post: 01-09-2009, 12:41 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  5. Replies: 1
    Last Post: 09-10-2005, 06:02 AM