gpt4 book ai didi

c++ - 从文件名中提取数字

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:14 25 4
gpt4 key购买 nike

我正在使用 C++ 处理文件名。我需要知道如何提取文件名的某些部分?文件名如下:

/home/xyz/123b45.dat

/home/xyz/012b06c.dat

/home/xyz/103b12d.dat

/home/xyz/066b50.dat

我想从每个文件名中提取“b”后的两位数(45、06、12、50)并存储在一个数组中。任何人都可以建议如何去做......

最佳答案

使用std::string::findstd::string::substr :

int main()
{
std::string line;
std::vector<std::string> parts;
while (std::getline(std::cin, line))
{
auto suffix = line.find(".dat");
if ( suffix != std::string::npos && suffix >= 2)
{
std::string part = line.substr(suffix-2, 2);
parts.push_back(part);
}
}

for ( auto & s : parts )
std::cout << s << '\n';

return 0;
}

输入的输出:

$ ./a.out < inp
45
06
12
50

或者,如果您绝对确定每一行都格式正确,您可以将循环内部替换为:

std::string part = line.substr(line.size()-6, 2);
parts.push_back(part);

(不推荐)。

编辑:我注意到您更改了问题的标准,因此这是新标准的替换循环:

auto bpos = line.find_last_of('b');
if ( bpos != std::string::npos && line.size() >= bpos+2)
{
std::string part = line.substr(bpos+1, 2);
parts.push_back(part);
}

请注意,所有这些变体都具有相同的输出。

你可以扔掉一个 isdigit也有很好的措施。

最终编辑:这是完整的bpos版本,兼容c++98:

#include <iostream>
#include <vector>
#include <string>

int main()
{
std::string line;
std::vector<std::string> parts;
// Read all available lines.
while (std::getline(std::cin, line))
{
// Find the last 'b' in the line.
std::string::size_type bpos = line.find_last_of('b');
// Make sure the line is reasonable
// (has a 'b' and at least 2 characters after)
if ( bpos != std::string::npos && line.size() >= bpos+2)
{
// Get the 2 characters after the 'b', as a std::string.
std::string part = line.substr(bpos+1, 2);
// Push that onto the vector.
parts.push_back(part);
}
}

// This just prints out the vector for the example,
// you can safely ignore it.
std::vector<std::string>::const_iterator it = parts.begin();
for ( ; it != parts.end(); ++it )
std::cout << *it << '\n';

return 0;
}

关于c++ - 从文件名中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16562650/

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