如何从特定格式的字符串流中读取数字?

时间:2019-04-10 19:24:32

标签: c++ string file stream

我有一个很大的文件,其中包含几何对象及其旁边的坐标。 格式如下: 矩形,(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不能满足我的要求,我已经做了很多搜索,找不到类似的东西可以对字符串流执行我想做的事情。

1 个答案:

答案 0 :(得分:2)

我的建议:

  1. 用字符串中的空格字符替换所有多余的字符。
    (),都可以用空格代替。
  2. 从简化的字符串中提取数字。

第一步,可以将"rectangle,(42,25),(68,25),(68,70),(42,70)"转换为"rectangle 42 25 68 25 68 70 42 70 "

直接从这样的字符串中读取数字。