操纵输入文件流 [英] Manipulate Input File Stream
问题描述
我有一个数据文本文件,其中包含以下内容
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, 68]
Map3D, [6, 9, 5]
Map2D, [3, 2]
Dot3D, [70, -120, -3], [-29, 1, 268]
Dot3D, [7, 12, 3], [-9, 13, 68]
Map3D, [1, 3, 8]
Dot2D, [5, 7], [3, 8]
基本上是文本文件的第一个数据是我获得4个班级的班级名称
Basically the text file first data is the class name which i got 4 class
Map2D
Map3D
Dot2D
Dot3D
我正在尝试编写自己的文件操纵器,以便我的程序可以提取上面的数据并重载提取对于这4个类别中的每个类别,然后将其存储到相关对象中。
I was trying to write my own file manipulator so that my program can extract the data above and overload the extraction operator >> for each of the 4 class and then storing it into relevant object.
我当时正在考虑使用vector,map,set或list进行存储。
I was thinking of using vector, map, set or list to store . but for this how do i achieve what i want to do such as store into relevant object of the class.
我尝试使用谷歌搜索方法来创建自己的文件操纵器,但是如果有人可以给我看一些示例代码,并且我可以在测试文件中编译并执行它,然后自己观察输出,那将是很好的。我想使用iomanip对>>运算符进行重载
I tried googling around on how to create my own file manipulator, but will be good if someone could show me some sample code and i can compile and execute it maybe in a test file then observe the output myself. I would like to use iomanip to do a overload on the >> operator
我必须使用操纵器,因为我需要创建类似
I have to use manipulator because i need create something like
我需要做
cout << "Input File Name";
cin >> readFile;
并执行所有数据读取和处理;创建对象
and perform all the data reading & object creation
对于造成的所有麻烦,我深表歉意。然后它将逐行读取记录,然后创建类以及其中的数据。
I am sorry for all the trouble caused. then it will read the records line by line, then create the class and also the data in it.
感谢您的所有帮助!
推荐答案
这是 std :: cin
的示例。 fstream
应该可以正常工作。解析您的输入确实很讨厌。是否可以从输入中删除方括号( [ amd])?
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;
}
}
}
这篇关于操纵输入文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!