Manipulate Input File Stream

前端 未结 2 2079
余生分开走
余生分开走 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 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    class Map2D {
        std::vector 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;
            }
        }
    }
    

提交回复
热议问题