简体   繁体   English

如何从文本文件中动态提取负数和正数?

[英]How to dynamically extract both negative and positive numbers from a textfile?

I have obtained a line in textfile that says for example: 我在文本文件中获得了一行,例如:

XCoordRange=0-8 XCoordRange = 0-8

Now that would be easy, i can just do a simple ifstream and read it to a string line and proceed to map and convert 现在这很容易,我可以执行一个简单的ifstream并将其读取为string line然后继续进行映射和转换

line[12] to int x1 第[12]行到int x1

and line[14] to int x2 . 和line [14]到int x2

This way, i am able to parse the values into my x1 and x2 coordinates. 这样,我能够将值解析为我的x1x2坐标。

However, things get tricky when different scenarios appear such as : 但是,当出现不同的情况时,事情变得棘手,例如:

XCoordRange=-10--5 (both negative) XCoordRange = -10--5(均为负)

XCoordRange=-10-5 (one negative and one positive) XCoordRange = -10-5(一负一正)

XCoordRange=10--5 (one positive and one negative) XCoordRange = 10--5(一正一负)

So my question is how can i dynamically map numbers in different scenarios into my x1 and x2 ? 所以我的问题是如何在不同的情况下将数字动态映射到我的x1x2

It seems as though i can only read one type of data (negative or positive) and not both (negative and positive). 似乎我只能读取一种类型的数据(负或正),而不能同时读取两种数据(负和正)。

Below is what i've tried so far: 以下是我到目前为止尝试过的方法:

    string line = "XCoordRange=-10-5";  
    size_t pos = 0;     
    string token;   
    string delimiter = "=";

    if(pos = line.find(delimiter) != string::npos)
    {
                    token = line.substr(0, pos);
                    line.erase(0, pos + delimiter.length());
    }

This gives me an output of -10--5 , however, i am stuck in what i should do next. 这给了我-10--5的输出,但是,我陷入了下一步的工作。

You can use istringstream defined in <sstream> as follows 您可以按以下方式使用在<sstream>定义的istringstream

// if line is "-10--5"
std::istringstream iss(line);
int n1, n2;
iss >> n1; // read first number ("-10")
iss.ignore(); // ignore the '-' character
iss >> n2; // read the second number ("-5")
   size_t equalPos = line.find("=");
   size_t dashPos = line.find("-", equalPos + 2);
   int x1 = stoi(line.substr(equalPos + 1, dashPos - equalPos - 1));
   int x2 = stoi(line.substr(dashPos + 1));

Of course, if you're not sure that the string line will always match the given pattern, then you need to add some checks. 当然,如果你不知道该串line将始终与给定的模式,那么你需要添加一些检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM