如何编写正确的“布尔”功能?

时间:2019-08-09 07:04:32

标签: c++ search char

我的代码有问题。我在int main()上方写了一个bool函数:

bool currency_(const char c)
{
    while (c==' ')
    {
        if (c==('p', 't', 'e', 'd'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

我希望程序能够运行,但是在编译时会显示“控制到达无效功能的末尾”。

4 个答案:

答案 0 :(得分:6)

您的功能没有意义。

如果package control; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import gui.FuzzyGUI; import model.GetValues; public class RunBtnListener implements ActionListener { FuzzyGUI menu; String logs[]; String CSVpathname; String XESpathname; public void actionPerformed(ActionEvent e) { // Drop previous temp log GetValues.dropTempLog(); // Recover log table names from splitting if(!SplitListener.tableName.equals("none")) { logs = GetValues.getLogsNames(SplitListener.tableName, 1); // 1 - Split } else { // recover (single) log table name from filtering logs = GetValues.getLogsNames(FilterListener.tableName, 0); // 0 - Filter } try { for(int i = 0; i < logs.length; i++) { CSVpathname = "res/log" + i + ".csv"; XESpathname = "res/log" + i + ".xes"; GetValues.exportToCSV(logs[i], CSVpathname); GetValues.convertToXES(CSVpathname, XESpathname); menu = new FuzzyGUI(XESpathname); } } catch (SQLException e1) { e1.printStackTrace(); } } } 是空格字符,则您的c语句(您是否正确编写了该语句,是否正确)将始终为false。

如果if不是空格字符,则函数以未定义的返回值退出。

您的c是无用的,因为该函数永远不会修改while

您可能想写这样的东西:

c

或者简单地

bool currency_(const char c)
{
    if (c =='p' || c == 't' || c == 'e' || c == 'd')
    {
        return true;
    }
    else
    {
        return false;
    }
}

答案 1 :(得分:3)

if (c == 'p' || c == 't' || c== 'e' || c == 'd')

组成代码并希望它是正确的C ++不是一个好主意。它很少起作用。

但是,即使进行了此更正,您在控制达到非空函数结束时的其他问题仍然存在。如果c不等于' ',您期望代码返回什么?

然后您还有另一个问题,就是如果c等于' ',那么它就不能等于'p''t''e'或{{1} }。因此,您的代码也存在一些逻辑问题。

答案 2 :(得分:3)

while (c==' ')
    {
        if (c==('p', 't', 'e', 'd'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

如果为c != ' ',则永远不会进入while循环的主体,并到达非void函数的末尾,而不返回任何内容,从而调用未定义的行为。

此外,if (c==('p', 't', 'e', 'd'))并没有您认为的那样。 您应该像这样连锁||运营商

if(c == 'p' || c == 't' || c == 'e' || c == 'd'){...}

或者,您可以使用std::arraystd::find

constexpr std::array<char,4> characters{'p', 't', 'e', 'd'};
if(std::find(characters.cbegin(), characters.cend(), c) != characters.cend()) {...}

答案 3 :(得分:1)

将这些字符放入向量中,并尝试在其中找到c:

std::vector<char> options{'p', 't', 'e', 'd'};
bool currency_(const char c)
{

    if (std::find(options.begin(), options.end(), c) != options.end())
    {
        return true;
    }
    else
    {
        return false;
    }

}

甚至更好的是直接返回std::find的结果:

bool currency_(const char c)
{
    return (std::find(options.begin(), options.end(), c) != options.end())
}