什么是Scala:getline(),std :: cin.eof(),std :: cin.bad()?

时间:2011-07-18 22:55:18

标签: c++ scala getline cin

这是C ++代码的一个片段:

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 << 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;
    }

Scala会为这些做什么:

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

1 个答案:

答案 0 :(得分:4)

在Scala(和Java)中,达到eof意味着在尝试阅读时获取null。我不知道cin.bad如何翻译,但可能是例外。

您的示例相当于:

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)
  }