我正在为我的高级CFD课程开发一个可压缩求解器。我需要运行多个模拟,所以我希望从命令行输入,这将允许我使用一些脚本来同时运行所有模拟。我目前从命令行获取文件名,并打开文件以循环遍历每行。我使用以下代码实现这一点:
// If input file is properly provided, try to read values from it
else
{
std::ifstream input(input_file); // Read input file
// Check if mesh is opened, return error otherwise
if(input.is_open())
{
std::string var; // Store the variable that is being populated
std::string val; // Store the value as a string
// Loop through each line of the input file
while(true)
{
input >> var >> val;
// Check which variable is being populated and assign value appropriately
// Definitely better way to do this, but if it ain't broke don't fix it
if (var == "CFL:")
{
CFL = std::stod(val);
}
else if (var == "nx:")
{
nx = std::stoi(val);
}
else if (var == "xbegin:")
{
xbegin = std::stod(val);
}
else if (var == "xend:")
{
xend = std::stod(val);
}
else if(var == "dt:")
{
dt = std::stod(val);
}
else if (var == "gamma:")
{
dt = std::stod(val);
}
// Leave loop once end of line is reached
if(input.eof())
{
break;
}
}
// Close input file once we are done with it
input.close();
}
这在很大程度上是有效的,但我想知道是否有更好的方法来做到这一点,特别是如果我开始不得不添加额外的变量从输入文件中读取。我想避免多个else if语句,如果可能的话,使添加更多的变量更容易,我不确定是否有一种方法可以做到这一点。谢谢你的帮助。
1条答案
按热度按时间64jmpszr1#
您可以考虑使用unordered_map,但根据您想对代码执行的操作,这可能不一定是更好的方法。