【问题标题】:Read a file line by line in c++ (Translating code from Python to C++) [closed]在 C++ 中逐行读取文件(将代码从 Python 转换为 C++)[关闭]
【发布时间】:2020-05-23 09:24:30
【问题描述】:

我必须将代码从 Python 翻译成 C++,但我找不到翻译这部分的方法:

    with open(files.square, "r") as f: # files.square is a txt file
    lines = f.readlines()
    with open(files.bs, "a") as f:     # files.bs is a txt file
        for i, line in enumerate(lines):
            if line == "LINE\n": txt_line(i, line, lines)
            if line == "ARC\n": txt_arc(i, line, lines)
#The functions txt_line and txt_arc doesn't need to be translated

只需要翻译文件的打开(with open...)、读取(f.readlines...)和循环(for i, line in enumerate(lines))。

基本上,我想翻译所有代码,但我不知道如何翻译。

【问题讨论】:

  • 这里有很多关于如何在 C++ 中读取和附加到文本文件的教程和答案。此外,还不清楚您不理解代码的哪一部分。 txt_line()txt_arc 的定义不存在,并且这些(至少据我所知和在线快速搜索)不是内置的 Python 函数。如果您想将代码移植到 C++,您也必须为这些函数执行此操作。
  • 我编辑了我的帖子。希望对你有帮助
  • 再次:代码的哪一部分有问题?文件操作还是循环?或两者?如果是循环,您只需要增加一个变量i,同时遍历每一行并进行比较。
  • 我投票结束这个问题,因为太宽泛了
  • 你尝试了什么?

标签: python c++ file translation


【解决方案1】:

试试这样的:

void txt_line(int, std::string, std::vector<std::string>){}
void txt_arch(int, std::string, std::vector<std::string>){}

int main()
{
    std::ifstream firstFile("../square.txt");

    std::vector<std::string> contentOfFirstFile;

    std::string aLine;
    while(std::getline(firstFile, aLine))
    {
        contentOfFirstFile.push_back(aLine);
    }

    std::ifstream secondFile("../bs.txt");
    aLine.clear();

    int lineCounter = 0;
    while(std::getline(secondFile, aLine))
    {
        if(aLine == "LINE")
        {
            txt_line(lineCounter, aLine, contentOfFirstFile);
        }
        else if(aLine == "ARC")
        {
            txt_arch(lineCounter, aLine, contentOfFirstFile);
        }

        ++lineCounter;
    }

    std::cin.get();

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2010-10-18
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多