"Not all controlpaths return a value" / "control may reach end of non void function" 用 while 循环验证时?

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

我正在尝试验证不是整数 1、2 或 3 的输入。我正在使用 do/while 循环,但它不起作用,只是不断重复。怎么了?

#include <iostream>
#include <string>

using namespace std;

string decisionThing(int);


int main()
{
    int response;
    cout << "Enter the section you are in in\n";
    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/while 循环是真的(用户输入一些像 155"zebras" 这样的输入)。

问题是您的 while 循环 总是 return 为真。当您应该使用 && 时,您却使用了 ||。任何输入都是 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 但编译器不知道。如果该方法得到的数字不满足这两种情况,应该怎么办?它没有定义。因此,我们有一个路径让此代码不 return 指定给 return 字符串的函数中的任何内容。您可以 return 空字符串或抛出异常或像这样处理 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。该函数将立即 return 因此之后的任何操作都不会被执行。