【问题标题】:How can I read a numbers from a specifically formatted stringstream?如何从特定格式的字符串流中读取数字?
【发布时间】: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++ 书给了你一个使用 sscanfstd::stringstream 的例子——这本书不好,需要找一本更好的书。
  • 这不是书本上的,我把 sscanf 放在这里作为例子,说明我想像 sscanf 一样从字符串流中读取数据。
  • 提示parsing。您需要解析您读取的字符串。
  • 不,恐怕“我该怎么做”不是一个具体的问题。我的具体问题是“这是我的文字输入,这就是我使用std::stringstream 解析它的方式,但它失败了,并使流处于失败状态,为什么?”这是具体的问题。您需要先编写一些代码,如果它不起作用,请提供minimal reproducible example,任何人都可以使用它来重现问题。请阅读 stackoverflow.com 的help center 中的How to Ask 问题。 stackoverflow.com 并不是一个真正的教程网站,有人去那里学习如何做某事。

标签: c++ string file stream


【解决方案1】:

我的建议:

  1. 将字符串中的所有无关字符替换为空格字符。
    (), 都可以替换为空格。
  2. 从简化字符串中提取数字。

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

从这样的字符串中读取数字很简单。

【讨论】:

  • 我正要发布这个。在创建字符串流之前这样做确实可以简化一切。
  • 我想到了这个,但如果我能告诉程序将数据放在两个括号之间并用逗号分隔,那不是更强大吗?
  • 我只是喜欢更简单的代码。我写的代码越多,bug 就越多。
  • @MinaAshraf,更强大,如果你的意思是“非常极客”,那么是的。我不认为它更强大。
  • 完全同意,但是我要学习一种新技术,你能建议一种提取括号之间内容的方法吗?很多人都在做这个项目,如果我编辑了这个文件,它可能会破坏他们编写的所有代码。这就是为什么我认为我不能编辑文件
猜你喜欢
  • 1970-01-01
  • 2014-01-26
  • 2021-04-02
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
  • 2019-06-21
相关资源
最近更新 更多