【发布时间】: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++ 中