是否可以将"Read from file"函数分配给变量?

Is it acceptable to assign a "Read from file" function to a variable?

本文关键字:分配 函数 变量 file from Read 是否      更新时间:2023-10-16

所以我有从文件中读取数据的FRead函数。如果函数返回错误代码,我需要完成程序。这样做可以接受吗:

string check=FRead(vec);

然后放一些 if 语句,如果检查具有某些值,则完成程序。

当我调用函数时,它是程序中唯一的实例,显然我不能多次调用它。它似乎工作正常,但我不太确定这是否是正确的方法。那么有没有一种正确的方法来做我想做的事情呢?

我还有 KRead 函数从键盘读取输入,如果出现问题,它也会返回错误代码。我这样称呼它

if(KRead=='ERROR')
   return 1
可以

这样做吗?

使用错误代码或异常总是更好的。两者之间的选择取决于实现。我做了一些示例应用程序,大致解释了什么是字符串错误、错误代码和异常。

字符串错误

这将起作用,但它很丑陋,而且您不知道在不消除GenerateError()函数的情况下定义了哪些错误)。

#include <string>
#include <iostream>
class Example
{
public:
    std::string GenerateError(bool error)
    {
        if (error)
        {
            return "ERROR";
        }
        return "OK";
    };
};

int main() 
{
    Example example;
    if ("ERROR" == example.GenerateError(true))
    {
        return 1; // failure
    }
    return 0; // success
}

错误代码

使用enum指定可用的错误代码(在本例中为 OkErrorError2 )。这使代码更易于理解,并且可以避免错误。使用枚举,您还可以使用 switch .

#include <string>
#include <iostream>
enum ErrorCodes
{
    Ok = 0,
    Error,
    Error2
    //...
};
class Example
{
public:    
    ErrorCodes GenerateError(bool error)
    {
        if (error)
        {
            return ErrorCodes::Error;
        }
        return ErrorCodes::Ok;
    };
};

int main() 
{
    Example example;
    // Regular if statement
    if (ErrorCodes::Ok == example.GenerateError(true))
    {
        return 1; // failure
    }
    else
    {
        return 0; // success
    }
    // switch statement
    switch (example.GenerateError(true))
    {
    case Error:
    case Error2:
        return 1; // failure
        break;
    case Ok:
        return 0; // success
        break;
    }
    return 0;
}

异常

例外有点复杂,但绝对值得一试。当您想要强制函数的用户对错误执行某些操作时,请使用异常。当函数不需要对错误执行操作时,最好使用错误代码。

#include <string>
#include <iostream>
class CustomException :public std::exception{
public:
    CustomException(const std::string m) :strMessage(m){}
    ~CustomException(void);
    const char* what(){ return strMessage.c_str(); }
private:
    std::string strMessage;
};
class Example
{
public:
    void GenerateError(bool error)
    {
        if (error)
        {
            throw CustomException("Critical error");
        }
        return;
    };
};

int main() 
{
    Example example;
    try
    {
        example.GenerateError(true);
    }
    catch (CustomException ce)
    {
        std::cerr << ce.what() << std::endl;
        return 1; // failure
    }
    return 0; // success
}

在C++中处理错误条件的一个好方法是让函数在出现问题时抛出异常。然后,您可以在调用它时检查异常。请参阅 http://www.cplusplus.com/doc/tutorial/exceptions/。

完全没问题。 就像其他人说的那样,您可以使用错误代码而不是字符串。