在 c++ 中逐行读取文件(将代码从 Python 转换为 C++)

Read a file line by line in c++ (Translating code from Python to C++)

本文关键字:Python 转换 C++ 代码 c++ 逐行 读取 文件      更新时间:2023-10-16

我必须将代码从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 == "LINEn": txt_line(i, line, lines)
if line == "ARCn": txt_arc(i, line, lines)
#The functions txt_line and txt_arc doesn't need to be translated

只需要翻译文件的打开(带有 open...(、读取(f.readlines...(和循环(对于 i,枚举(行(中的行(。

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

尝试这样的事情:

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