reading x,y coordinates in text file c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fentahun
    New Member
    • Apr 2014
    • 3

    reading x,y coordinates in text file c++

    hi i need to read x,y coordinates in text file using c++
    the name of file is input.txt which is ,
    Code:
    x      y
    232.1,753.7
    100.5,981.6
    96.2,992.9
    148.7,953.2
    197.2,999.3
    249.9,998.6
    261.7,975.9
    262.4,905.8
    334.9,980.8
    371.6,979.4
    396.7,996.3
    405.1,995
    565.5,766
    459.4,988.5
    474.4,994.6
    594.6,996.8
    604,987.3
    612.8,877.3
    664.1,992.6
    please help me the following code was did not work. any other code is appretiated
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std
    
    struct monsters_struct {
    int x, y;
    };
    
    int main()
    { monsters_struct monsters[100]; //Create an array "monsters" as type "monsters_struct"
    ifstream inData("input.txt");
    for (int i=0; i<20; i++) {
    inData >> monsters[i].x >> monsters[i].y; //Read x and y coordinates at position i
    cout << monsters[i].x << " " << monsters[i].y << endl; //Output the x and y coordinates read above
    }
    inData.close();
    return 0;
    }
    Last edited by Rabbit; Apr 7 '14, 05:34 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • divideby0
    New Member
    • May 2012
    • 131

    #2
    Code:
    inData >> monsters[i].x >> monststers[i].y;
    
    // x  y (bad data)
    // 232.1,753.7  (good data, but wrong types)
    I believe the above code would fail when it encounters the wrong type of the comma since your file's data is float char float - eg: 123.4,567.8

    Code:
    typedef struct 
    {
        float x;
        float y;
    
    } monsters_struct;
    
    char delim;
    monsters_struct monsters[100] = { 0 };
    ...
    
    inData >> monsters[i].x 
           >> delim
           >> monsters[i].y
    If your data file has "x y" as the first line, then you'll want to skip reading that into your struct.

    If your file has the floating numbers, change x and y to floats or doubles.

    Comment

    Working...