【发布时间】: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