开发者

What is Scala for: getline(), std::cin.eof(), std::cin.bad()?

开发者 https://www.devze.com 2023-03-21 09:35 出处:网络
Here is a fragment of C++ code: int AskBase::ask_user(){ for (int tries_left = MAX_TRIES; tries_left;){

Here is a fragment of C++ code:

int AskBase::ask_user(){
   for (int tries_left = MAX_TRIES; tries_left;){
        std::cout << prompt.c_str();
        std::string response;
        getline(std::cin, response);
        if ("^Z" == response || std::cin.eof() || std::cin.bad())
            return -9;
        else if ("?V" == response)
            std::cout << SSVID_ICON << SSVID <<开发者_如何学JAVA; std::endl;
        else if ("?" == response)
            std::cout << "Enter ? for help, ?V for version, ^Z for exit.\n"
        else if (validate(response)){
            answer_string = response;
            return 1;
        else
            --tries_left;
       }
    return -9;
    }

What would the Scala be for these:

  • getline()
  • std::cin.eof()
  • std::cin.bad()


In Scala (and Java), reaching the eof means getting null when trying to read. I don't know how cin.bad translates, but it may be exceptions.

Your example is equivalent to:

def askUser( tries_left: Int = MAX_TRIES ):Int = 
  Console.readLine match {
    case "^Z" | null => -9
    case "?V" => {
      println( SSVID_ICON  + SSVID )
      askUser( tries_left )
    }
    case "?" => {
      println( "Enter ? for help, ?V for version, ^Z for exit.")
      askUser( tries_left )
    }
    case response if validate(response) => {
         answer_string = response
         1
    }
    case _ => if( tries_left == 0) -9 else askUser( tries_left - 1)
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消