Manipulate Input File Stream

前端 未结 2 2075
余生分开走
余生分开走 2020-12-21 20:16

I have a data text file which contains this

Map2D, [3, 2]
Dot3D, [25, -69, -33], [-2, -41, 58]
Map3D, [6, 9, -50]
Map2D, [3, 2]
Dot3D, [7, -12, 3], [9, 13, 6         


        
相关标签:
2条回答
  • 2020-12-21 20:38

    This is an example with std::cin. It should work just fine with a fstream. parsing your input is really nasty. Is it possible to remove the brackets("[" amd "]") from the input?

    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>
    #include <algorithm>
    #include <c>
    
    class Map2D {
        std::vector<int> values;
    public:
        friend std::istream& operator>>(std::istream& in, Map2D m) {
            std::string i;
            in >> i;
            std::stringstream ss(i);
            std::getline(ss, i, '[');
            std::getline(ss, i, ',');
            ss >> i;
            std::cout << i << std::endl;
            in >> i;
            ss.str("");
            ss << i;
            i = i.substr(0, i.size()-1);
            ss >> i;
            std::cout << i << std::endl;;
        }
    };
    
    int main() {
        std::string type, file_name;
        std::cout << "Input File Name";
        std::cin >> file_name;
        std::fstream file(file_name.c_str());
        Map2D m;
        while (std::getline(std::cin, type, ',')) {
            if(type.find("Map2D") != std::string::npos) {
                file >> m;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 20:45

    You can use the cin to get the filename, but then you should write a helper method that can parse the file.

    My suggestion would be to create a class called DataMembers or something like that. In that class you can have a helper method that reads in a data member file. The class could have 4 vectors for storing the data you read from the file.

    class DataMembers
    {
        private:
            std::vector<Map2D> _map2Ds;
            std::vector<Map3D> _map3Ds;
            ....
        public:
            void readDataFile(std::string inFileName);
            void writeDataFile(std::string outFileName);
    };
    

    The readDataFile method should do the following

    1. Read the file in a line at a time
    2. Parse the line to determine the object type to create (error out if the type is not recognized)
    3. Validate that the line contains the correct data for the type indicated
    4. Create the object of the proper type
    5. Assign the object to the proper object collection

    You would probably want to write some other private methods to handle the creation of the data types and assigning to the proper collections.

    0 讨论(0)
提交回复
热议问题