C ++:goto和用户输入不能一起工作

时间:2017-09-21 15:12:42

标签: c++ string authentication if-statement user-input

我正在使用C ++,并使用if语句的基本身份验证方法,所以我在这里,当输入不是所需的组合时,它会说Access拒绝并询问用户是否要尝试再次或退出。我尝试使用goto变量执行此操作,但它还没有工作。请帮忙? (完整代码:https://pastebin.com/49LdGgJX

    else {
    cout << "Access denied..." << " Try again? (Y/N) >" << flush;
    string ask;
    cin >> ask;
    if(ask == "N" || "n"){
      cout << "Shutting down..." << endl;
      goto end;
    }
    else if(ask == "Y" || "y"){
      goto restart;
    }

    else {
      cout << "Invalid option." << endl;
      goto restart;
    }
  }

  end:
  return 0;

2 个答案:

答案 0 :(得分:1)

您的if陈述错误为:

if(ask == "N" || "n") 

始终评估为true,因为"n"操作数始终评估为true,并且您使用的是逻辑OR运算符。 "n"的字符串文字衰减为const char*指针,其值不是0,因此评估为true。你想要的是:

if(ask == "N" || ask == "n")

else if(ask == "Y" || ask == "y")

据说不要使用goto

答案 1 :(得分:0)

可能将代码结构分解为更多程序化方式(不敢称之为“面向对象”)。 您可以使用类似的方法将菜单处理代码分解为每个选项的单独函数等。

如果这是多用户应用程序,那么您可能希望存储而不是经过身份验证的用户的简单true / false完整凭据,例如具有包含name, code的结构(密码可能在身份验证后被丢弃)如果以后不需要它,请不要长时间保存在内存中。)

// returns true if user wants to exit
// sets authenticated to true when the Drew user is detected
bool AuthenticateUser(bool & authenticated) {
  cout << "Enter your username >" << flush;
  ...
  if (name == "Drew" && ...) {
    authenticated = true;
    cout << "Access granted. Welcome, " << name << "." << endl;
    cout << "Welcome to Database of Drew" << endl;
    return false;
  }
  cout << "Access denied..." << " Try again? (Y/N) >" << flush;
  ...
  return (ask == "N" || ask == "n");  // N = wants to exit
}

// returns true if user wants to exit
bool ProceedWithMenu() {
  cout << "1.\tAdd new record." << endl;
  cout << "2.\tDelete record." << endl;
  ...
  if (1 == value) {
    ...
  }
  if (5 == value) {
    cout << "Application quitting... " << endl;
  }
  return (5 == value);
}

void mainLoop {
  bool authenticated = false;
  bool exitApp = false;

  do {
    if (!authenticated) {
      exitApp = AuthenticateUser(authenticated);
    } else {
      exitApp = ProceedWithMenu();
    }
    // repeat authentication / menu until user decides to quit app
  } while (!exitApp);
}

这个例子仍然非常粗糙和过于简单,只是试图说明do {} whilereturn和类似的力量。通常continuebreak也可以帮助控制代码执行流程,而不需要任何goto和标签。