“并非所有控制路径都返回一个值./&quot“控制可能达到非空隙功能的末端”.验证时循环时

"Not all controlpaths return a value" / "control may reach end of non void function" when validating with while loop?

本文关键字:控制 功能 能达到 验证 循环 quot 路径 返回 一个      更新时间:2023-10-16

我正在尝试验证不是整数1、2或3的输入。怎么了?

#include <iostream>
#include <string>
using namespace std;
string decisionThing(int);

int main()
{
    int response;
    cout << "Enter the section you are in inn";
    cin >> response;
    do
    {
        cout << "Are you in section 1, 2, or 3?";
        cin >> response;

    } while (response != 1 || response != 2 || response != 3);
    cout << decisionThing(response) << "n";
}
string decisionThing(int response)
{
    string date;
    switch (response)
    {
        case 1:
            date = "The test will be held on the 5th.n";
            return date;
            break;
        case 2:
            date = "The test will be held on the 6th.n";
            return date;
            break;
        case 3:
            date = "The test will be held on the 9th.n";
            return date;
            break;
    }
}

它应该执行do/wher loop是正确的(用户输入了一些输入,例如 155"zebras"(。

问题是您的while loop 始终返回true。当您使用&&时,您正在使用||。任何输入都是not 1not 2not 3

将您的代码更改为此,它将解决问题。

do {
    cout << "Are you in section 1, 2, or 3?";
    cin >> response;
} while (response != 1 && response != 2 && response != 3);

至于您遇到的错误,可能是您的decisionThing在现实生活中不会获得一个不是123的数字,但是编译器不知道。如果该方法获得了不满足任何一种情况的数字,应该会发生什么?它没有定义。因此,我们有一个路径,可以使该代码不返回指定返回字符串的函数中的任何内容。您可以返回空字符串或抛出异常或处理default案例:

string decisionThing(int response)
{
    string date;
    switch (response)
    {
        case 1:
            date = "The test will be held on the 5th.n";
            return date;
        case 2:
            date = "The test will be held on the 6th.n";
            return date;
        case 3:
            date = "The test will be held on the 9th.n";
            return date;
        default:
            date = "Wow, this is really unexpected, I guess nothing?n";
            return date;
    }
}

顺便说一句,当您拥有return时,您不需要break s。该函数将立即返回,因此之后的任何内容都无法执行。