【问题标题】:extract digits from filename从文件名中提取数字
【发布时间】:2013-05-15 10:28:40
【问题描述】:

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

/home/xyz/123b45.dat

/home/xyz/012b06c.dat

/home/xyz/103b12d.dat

/home/xyz/066b50.dat

我想从每个文件名中提取 'b' (45, 06, 12, 50) 之后的两位数并存储在一个数组中。任何人都可以请建议如何做到这一点...

【问题讨论】:

  • 您想从文件名中提取两位数字,还是想可视化一个向量的向量?
  • 向量的向量是一个老问题!这个问题是关于文件名的...... @juanchopanza
  • 对不起!!忘记标题了!! @juanchopanza

标签: c++ file filenames


【解决方案1】:

使用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;
}

【讨论】:

  • 嘿@BoBTFish!多谢!!您能否帮我解决我遇到的错误...它说:“错误:'bpos'没有命名类型”我该怎么办?谢谢!!!
  • 您没有使用c++11 支持进行编译。如果这不是一个选项,bpos 的类型是std::string::size_type(这就是我使用auto 的原因,很容易忘记或懒惰并使用错误的类型)。
  • 我在 C++98 模式下。它说:“错误:C++ 98 模式下不允许基于范围的 for 循环”我不明白这一点.....我在 C++ 方面不太先进...谢谢您的帮助...请建议如何实现循环然后...
  • @user2346085 这只是来自我的输出循环。您可以完全删除该位。我将在bpos 版本的c++98 版本中进行编辑,但您真的应该阅读c++11。您已经过时了 2 年,并且将会有一个 c++14。也许开始here
  • 非常感谢!我会尽快过去的!我等c++98版本。。。谢谢!!!
【解决方案2】:

考虑到您的问题的标题,我假设您将文件名存储为vectorschars。一个更好的方法是使用std::strings。字符串允许各种设施功能,包括子字符串的标记和检索等(这是您想要做的)。

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 2011-01-01
    • 1970-01-01
    • 2016-08-20
    • 2015-09-01
    • 2020-12-28
    • 2012-04-25
    • 2012-10-18
    • 1970-01-01
    相关资源
    最近更新 更多