首页 > 解决方案 > 从 C++ 函数安全关闭程序

问题描述

我想制作一个程序,在读取用户输入文件后执行一些数学运算。

在读取过程中(一个函数),我想检查文件中的用户语法是否正确,否则我想关闭程序,以便用户可以相应地修改文件(s=并再次运行它。

结构将是这样的:

int main(int argCount, char *args[])
{
   std::string fileName = "PathOfFile";
   int a = GetUserInput(fileName, variableName);
   int b = GetUserInput(fileName, variableName);

   // Other functions will be placed here
   return 0;
}

int GetUserInput(std::string filename, std::string variableName)
{
 // Some routine to read the file and find the variableName 
 // Some routine to check the syntax of the user input. 
    // Let us assume that the integers are to be fined as: variableName 1;
    // and I want to check that the ; is there. Otherwise, shutdown the program.     
}

如何从该功能安全地关闭程序GetUserInput?是否有任何 C++ 表明程序必须结束并退出?

标签: c++c++11

解决方案


有许多不同的方法可以做到这一点,不同之处主要在于风格、个人偏好以及您熟悉 C++ 库的哪些部分。

  1. 解析函数只是调用exit().
  2. int该函数不返回值设置,而是将指针或对int值的引用作为附加参数并设置它(如果有效)。bool相反,该函数返回 a以指示它是否解析了有效设置。main()检查返回的bool值,以及它本身return的 from main(),结束程序。
  3. 解析函数返回 a std::optional<int>而不是返回 astd::nullopt以指示解析失败。main()检查返回的值,以及它本身return的 from main(),结束程序。
  4. 解析函数抛出一个被捕获的异常,main异常处理程序return来自main

每个替代方案都有其自身的优点和缺点。您可以自行决定哪种方法最适合您的程序。


推荐阅读