【发布时间】:2019-09-01 08:20:46
【问题描述】:
我有一个巨大的文件,其中包含几何对象及其旁边的坐标。 格式是这样的: 矩形,(42,25),(68,25),(68,70),(42,70)
我想单独读取每个数字并将其存储在数组中,以便稍后处理这些数据以查找形状区域和周长。
string line = ""; // A string for reading lines from the text file
ifstream readFile("Input_Points.txt"); // Opening the input file
string name = ""; // A string to store the type of the shape
while(getline(readFile,line)) {
// Loop through the file lines
stringstream iss(line); // Instantiate stringstream with the current line just read
getline(iss, name, ','); // Parse token until the first comma and store it in name
Shape * obj = gobj[name]; //Fetch the corresponding object from map using name
if ( obj != NULL ) {
// If it can find an object with name index
obj = obj->clone(iss); // Clone an object of the same type
cout << name << ":" << obj->area() << ":" << obj->perimeter() << "\n"; // Calculate area and print it
delete (obj); // delete the object
}
else
cout << "Undefined Object Identifier\n"; // Cannot find object type in map
}
这两个功能是我处理数据
void Square::initialize (stringstream & ss)
{
for (int i = 0; i < 2; i++) {
sscanf(ss,",(%lf,%lf)", points[i].X, points[i].Y);
}
for (int i = 0; i < 2; i++) {
LineLength[i] = points[(i + 1)%2] - points[i];
}
}
Shape * Square::clone (stringstream & ss) { //can be done with templates
Square * square = new Square();
square->initialize(ss);
return square;
}
sscanf 在这里没有做我想做的事,我做了很多搜索,但找不到类似的东西可以在字符串流上执行我想做的事情。
【问题讨论】:
-
正则表达式?
-
当然“sscanf 不会做你想做的事”。如果它甚至不编译,它就不能做很多事情。 sscanf 是一个 C 库函数,它对 C++ 流一无所知。哪本 C++ 书给了你一个使用
sscanf和std::stringstream的例子——这本书不好,需要找一本更好的书。 -
这不是书本上的,我把 sscanf 放在这里作为例子,说明我想像 sscanf 一样从字符串流中读取数据。
-
提示parsing。您需要解析您读取的字符串。
-
不,恐怕“我该怎么做”不是一个具体的问题。我的具体问题是“这是我的文字输入,这就是我使用
std::stringstream解析它的方式,但它失败了,并使流处于失败状态,为什么?”这是具体的问题。您需要先编写一些代码,如果它不起作用,请提供minimal reproducible example,任何人都可以使用它来重现问题。请阅读 stackoverflow.com 的help center 中的How to Ask 问题。 stackoverflow.com 并不是一个真正的教程网站,有人去那里学习如何做某事。