gpt4 book ai didi

c++ - 读取带有分隔符的文本文件

转载 作者:行者123 更新时间:2023-11-28 03:28:20 26 4
gpt4 key购买 nike

我有一个文本文件,内容是

Point1, [5, 6]
Line2, [1, 2, 3], [-5, 55, 33]
Point2, [5, 3, 1]
Line1, [1, 2], [5, 7]

我会做比较,比如第一个变量 (Point1, Line2, Point2, Line1)

如果是point1,则存入point 1数组,x设为5,y设为6。

如何将分隔符设置为逗号以及“[”和“]”。我只需要变量 Point1、5 和 6 来相应地存储它们。

最佳答案

我会用最简单的方法解决这个问题 - 使用 getline 读取文件,然后替换所有出现的 , , []带空格。然后您可以使用 std::istringstream 读取所有输入来自 <sstream> .您也可以使用正则表达式(如果您使用 boost 或 c++-11),但我相信我的建议应该可以完成这项工作。

编辑:这是一个如何按照我的建议去做的例子。我只会向您展示如何输入点,以及如何处理线,您必须添加一个基于名称的 if 语句。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
string line;

while (getline(cin, line)) {
for (unsigned i = 0; i < line.size(); ++i) {
if (line[i] == '[' || line[i] == ']' || line[i] == ',') {
line[i] = ' ';
}
}
istringstream in(line);

string name;
double x,y;
in >> name >> x >> y; // Point1 <x> <y>
... do something with the point...
}

return 0;
}

您也可以使用 replace_if来自 <algorithm>替换符号,但我认为您可以更轻松地理解此解决方案。

关于c++ - 读取带有分隔符的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13320698/

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