【问题标题】:Translating a function from Python to C++将函数从 Python 转换为 C++
【发布时间】:2022-01-04 14:51:25
【问题描述】:

我正在为 Python 中的某个函数苦苦挣扎,这并不复杂,但我需要用非常有限的先验知识将它“翻译”成 C++。

def BuildCommandList(commands : list, filepath : str):

    commands.clear()

    try:
        file = open(filepath, 'r')
    except FileNotFoundError:
        return False

    for line in file:
        line = line.replace('\n','')

        if len(line) != 0:      
            line = line.split()             
            commands.append(line)
    file.close()

    return True

上面是 Python 中的函数,下面是我目前在 C++ 中做同样事情的尝试

bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
    
    std::ifstream test(filepath);
    test.open(filepath);

    if (test.is_open())
    {
        std::string line, text;
        while (std::getline(test, line))
        {
            if (!line.empty() || line.find_first_not_of(' ') == std::string::npos)
            {
                text += line + "\n";
            }

            if (len(line) != 0); //Obviusly doesn't work
            {

            }
        }
    }

    else
    {
        return false;
    }


    return true;
}

感谢所有帮助

【问题讨论】:

  • 您的尝试有什么问题?代码应该做什么,它做了什么?
  • 你能解释一下“挣扎”是什么意思吗?显示的 C++ 代码的哪一部分不适合您?你期待什么结果?你得到什么结果?当您使用调试器运行您的 C++ 程序时,一次一行,并在结果不同时显示所有变量的值,您看到了什么?
  • 我真的不知道到目前为止我的尝试是否一定是错误的,它还没有真正“做”任何事情,程序本身就是一个汇编程序?它读取汇编文件,现在我坚持尝试制作这个功能,它打开一个文件并读取它,但我不知道如何执行“if len(line)!= 0:......”部分在 C++ 中

标签: python c++


【解决方案1】:

Python 的len 的自然等价物是std::size,或者等价于std::stringsize 成员。但是,您可能更喜欢std::stringempty 成员来满足您的条件。

然后您需要拆分字符串。这可以通过 std::stringstreamstd::istream_iterator 在适当的位置构造 std::vector&lt;std::string&gt;(重载 5)来完成。

注意getline不包含\n,所以拆分前不需要修改line

bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
    commandList.clear();

    std::ifstream test(filepath);
    if (!test)
    {
        return false;
    }

    for (std::string line; std::getline(test, line); )
    {
        if (!line.empty())
        {
            using iterator = std::istream_iterator<std::string>;
            commandList.emplace_back(iterator{std::stringstream{line}}, iterator{});
        }
    }

    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-08-15
    相关资源
    最近更新 更多