【问题标题】:How to get a number in a line after a certain sequence of characters which can vary in number of delimeters?如何在分隔符数量不同的特定字符序列之后获取一行中的数字?
【发布时间】:2020-11-26 09:01:19
【问题描述】:

我正在逐行读取输入 txt 文件并尝试获取某一行并从中提取一个数字。该行可能如下所示:

"; Max: 144"
";  Max: 28292"
";   Max: 283829"
";Max: 12"

所以基本上它可以在“Max:”之前有任意数量的分隔符。我试图用 line.find(...);它告诉我给定的序列是否在行中,然后使用 line.erase(...) 从其中删除不需要的字符串,但我必须检查每一种可能性,所以它没有很好地编程并且容易出错。它看起来像这样:

size_t pos = line.find("; Max: ");
size_t pos1 = line.find(";  Max: ");
size_t pos2 = line.find(";   Max: ");
if (pos != -1)
     {
         std::string x = "; Max: ";
         size_t l = x.length();
         procs = std::stoi(line.erase(pos, l));
     }else if(pos1 != -1){
         std::string z = ";  Max: ";
         size_t l = z.length();
         procs = std::stoi(line.erase(pos1, l));
     }else if(pos2 != -1){
         std::string o = ";   Max: ";
         size_t l = o.length();
         procs = std::stoi(line.erase(pos2, l));
     }
...

我也尝试使用正则表达式,但它使我的程序减慢了大约 8 倍,这是非常不需要的。如何快速正确地提取数字?

【问题讨论】:

    标签: c++ string find string-parsing


    【解决方案1】:

    Here 有一个智能解决方案。使用find_first_of 检测第一个数字,然后提取该行的其余部分。

    auto found = line.find_first_of("123456789");
    if (found != std::string::npos)
    {
        procs = std::stoi(line.substr(found));
    }
    

    假设该行中没有其他数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多