gpt4 book ai didi

c++ - 逐行读取具有不同行长的整数

转载 作者:行者123 更新时间:2023-11-30 05:25:24 25 4
gpt4 key购买 nike

我有这个文本文件,每一行代表一个多边形的顶点。

(-189, 102), (-62, 113), (-40, 56), (-105, -11)
(-692, 403), (-669, 308), (-572, 273)
(-750, 480), (750, 480), (750, -480), (-750, -480)
(57, -218), (47, -270), (134, -366), (235, -366), (300, -260), (335, -182)

如何读取每个顶点 x 和 y 并将它们存储到 int 变量中。请注意,每行可以有不同数量的对。我还想逐行执行此操作,以便我知道文件中何时开始新的多边形。

我正在尝试获取每一行,但是我该怎么做才能从该行中提取整数?

int main() {
string line;
ifstream myfile("input.txt");
if (myfile.is_open())
{
while (getline(myfile, line))
{
//cout << line << '\n';
stringstream stream(line);

}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

最佳答案

你得到 line正确。你只需要建立一个容器(我将使用 vector<vector<pair<int,int>> foo 。)然后你可以只使用 regex_iterator 为您提取信息。我会使用这样的东西:

\s*,?\s*\(\s*([-0-9]+)\s*,\s*([-0-9]+)\s*\)

Live Example

然后,一旦你得到 line你可以像这样使用你的正则表达式:

regex re(R"~(\s*,?\s*\(\s*([-0-9]+)\s*,\s*([-0-9]+)\s*\))~");
vector<pair<int, int>> temp;

transform(sregex_iterator(cbegin(line), cend(line), re), sregex_iterator(), back_inserter(temp), [](const auto& it) { return make_pair(stoi(it[1]), stoi(it[2])); });
foo.push_back(temp);

Live Example

编辑:

如果您选择了最简单的定界方案,即使用空格和换行符来定界您的输入,则可以避免使用正则表达式。这可能是可取的,但您不会看到任何性能变化,因为几乎任何方法都可以用文件 IO 开销来注销。尽管如此,如果您得到了输入:

-189 102 -62 113 -40 56 -105 -11
-692 403 -669 308 -572 273
-750 480 750 480 750 -480 -750 -480
57 -218 47 -270 134 -366 235 -366 300 -260 335 -182

一旦您再次获得 line你可以这样做:

istringstream stream(line);
vector<pair<int, int>> temp;

for(pair<int, int> i; stream >> i.first >> i.second;) temp.push_back(i);
foo.push_back(temp);

Live Example

关于c++ - 逐行读取具有不同行长的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38265654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com