void操作符用于调用菜单

时间:2017-05-16 11:31:54

标签: c++

所以我有这部分代码而且我有这些错误而不是我发布如何修复它们。谢谢你的帮助..

void DisplayMenu()
{
    cout <<"Please choose from the following options :\n\n"
         <<"1-al.\n"
         <<"2-c.\n"
         <<"3-v.\n\n"
         <<"Or I want to see first :\n"
         <<"------------------------\n\n"
         <<"4-r.\n"
         <<"5-m.\n"
         <<"6-k.\n"
         <<"7-d.\n"
         <<"8-u.\n\n"
         <<"Or :\n"
         <<"----\n\n"
         <<"9-I changed my mind and would like to exit.\n\n";
}

int ChooseFromMenu()
{
    int A =0 ;
    while ((DisplayMenu() && !(cin >> A ) || (cin.good() && (A < 1 || A > 9))) {
    cout << "\nInvalid input!\n"<<endl;
    cin.clear();
    cin.ignore(1000, '\n');
    }
    return A;
}

这是我的错误列表

3   IntelliSense: expected a statement  
2   IntelliSense: expected a ')'  
Error   1   error C4716: 'DisplayMenu' : must return a value

3 个答案:

答案 0 :(得分:1)

您在while循环参数中错过了条件:

while ((DisplayMenu() && !(cin >> A ) || (cin.good() && (A < 1 || A > 9)))

正如您从定义中看到的,DisplayMenu正在返回void,您正试图将其与boolean值进行比较(此处为 - &gt; while ((DisplayMenu())。< / p>

要解决此问题,您可以将DisplayMenu方法更改为仅返回boolean值:

bool DisplayMenu()
{
    // your logic

    return true;
}

Complete working example

#include <iostream>

using namespace std;

int DisplayMenu()
{
    cout <<"Please choose from the following options :\n\n"
                 <<"1-al.\n"
                 <<"2-c.\n"
                 <<"3-v.\n\n"
                 <<"Or I want to see first :\n"
                 <<"------------------------\n\n"
                 <<"4-r.\n"
                 <<"5-m.\n"
                 <<"6-k.\n"
                 <<"7-d.\n"
                 <<"8-u.\n\n"
                 <<"Or :\n"
                 <<"----\n\n"
                 <<"9-I changed my mind and would like to exit.\n\n";

    return 1;
 }

int ChooseFromMenu()
{   
    int A =0 ;
    if ((DisplayMenu() && !(cin >> A )) || (cin.good() && (A < 1 || A > 9))) {
        cout << "\nInvalid input!\n"<<endl;
        cin.clear();
        cin.ignore(1000, '\n');

    }
    return A;
}

答案 1 :(得分:1)

如果确实想在while循环的条件下使用DisplayMenu,则需要使用逗号运算符:

int ChooseFromMenu()
{
    int A =0 ;
    while (DisplayMenu(), (!(cin >> A ) || (cin.good() && (A < 1 || A > 9))) {
        cout << "\nInvalid input!\n"<<endl;
        cin.clear();
        cin.ignore(1000, '\n');

    }
    return A;
 }

这将调用DisplayMenu,抛出(不存在的)返回值,然后评估实际情况。然而,就个人而言,我会使用带有条件中断的无限循环:

int ChooseFromMenu()
{
    int A =0;
    while (true) {
        DisplayMenu();
        if ((cin >> A)) {
            if (!cin.good() || (1 <= A && A <= 9)) {
                return A;
            }
        }
        cout << "\nInvalid input!\n"<<endl;
        cin.clear();
        cin.ignore(1000, '\n');
    }
}

我已将条件拆分为两个嵌入式if,因为我发现它比&&||的组合更容易阅读。 (我也喜欢在组合多个比较时总是使用<<= - 我觉得它更容易阅读。)

答案 2 :(得分:0)

您在ChooseFromMenu()中的while循环中忘记了一个括号。这可能导致2个错误。由于返回true不起作用,您可能忘记将方法头从void更改为boolean。 (cin&gt;&gt; A)也返回void。