在C ++中,我怎样才能使cin"取消"如果按下返回键?

时间:2016-01-13 00:16:44

标签: c++ cin

我试图通过编写一个简单的控制台应用程序来学习C ++。用户通过输入存储在变量中的数字来导航主菜单,然后switch语句用于确定要执行的操作。这很简单。 :)

困扰我的问题是,当程序到达cin语句时,按回车而不输入数字不会退出"声明,但只是碰到下一行。我想这是有道理的,但我怎么能让它如此紧迫的回归而没有先前的输入只是"退出"或者"取消" cin声明?

下面简要介绍了我的应用程序的样子:

int main()
{
    int mainMenuSelector;

    while(mainMenuSelector != 4){
        cout << "--- MAIN MENU -----------------" << endl;
        cout << "[1] First Option" << endl;
        cout << "[2] Second Option" << endl;
        cout << "[3] Third Option" << endl;
        cout << "[4] Exit Application" << endl;
        cout << "-------------------------------" << endl;
        cout << "Selection: ";

        cin >> mainMenuSelector;
        // This is the statement I want to move along from
        // if the user presses the return key without entering any input.

        switch(mainMenuSelector){
            case 1:
                doSomething();
                break;
            case 1:
                doSomething();
                break;
            case 2:
                doSomething();
                break;
            case 3:
                doSomething();
                break;
        }
    }
    return 0;
}

3 个答案:

答案 0 :(得分:3)

std::string input;
while (std::getline(std::cin, input) && !input.empty()) { /* do stuff here */ }

你可能想要进一步验证输入是否有效,不只是有一堆空格等......

答案 1 :(得分:1)

在没有输入的情况下按Enter键会产生空字符串值。 你可以这样做(尝试并使其适应你的代码):

#include <string>
#include <iostream>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    while(s != "") { // if the person hits enter, s == "" and leave the loop
        cout << s << endl;
        getline(cin, s);
    }
    return 0;
}

答案 2 :(得分:1)

如果你专门寻找使用流操作符的选项(而不是自己解析输入),你可以考虑使用std :: stringstream。例如:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lobster|Oswald|Titillium Web|Roboto  ">

    <title>Starter Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="../../dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="starter-template.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="../../assets/js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script>
      function initialize() {
        var mapCanvas = document.getElementById('map');
        var myLatLng = {lat: 64.8370761, lng: -147.697845};
        var mapOptions = {
          center: myLatLng,
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: "Nelson's Photography"
        });
      }

        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
            initialize();
        });

    </script>
  </head>



  <body>
    <nav class="navbardos navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#"><img src="/images/titlegraphic.jpg" class="logo"></a>
        </div>
          <ul class="nav navbar-navdos">
            <li><a class="number">(907)452-3116</a></li>
            <li><a>606 Bentley Drive | Fairbanks, AK</a></li>
          </ul>
      </div>
    </nav>
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav nav-pills">
            <li class="active"><a data-toggle="pill" href="#home">Home</a></li>
            <li><a data-toggle="pill" href="#about">About</a></li>
            <li><a data-toggle="pill" href="#services">Services</a></li>
            <li><a data-toggle="pill" href="#portfolio">Portfolio</a></li>
            <li><a data-toggle="pill" href="#contact">Contact</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <div class="tab-content">

      <div id="home" class="tab-pane fade in active">
        <div id="myCarousel" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
        <li data-target="#myCarousel" data-slide-to="1"></li>
        <li data-target="#myCarousel" data-slide-to="2"></li>
      </ol>
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img class="first-slide" src="/images/10x10reflect-lg.jpg" alt="First slide">
          <div class="container">
            <div class="carousel-caption">
              <h1>Music Production Studio</h1>
              <p></p>
              <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn More</a></p>
            </div>
          </div>
        </div>
        <div class="item">
          <img class="second-slide" src="/images/11830247_10207115344978900_1142161344_n.jpg" alt="Second slide">
          <div class="container">
            <div class="carousel-caption">
              <h1>Beat Gallery</h1>
              <p></p>
              <p><a class="btn btn-lg btn-primary" href="#" role="button">Listen</a></p>
            </div>
          </div>
        </div>
        <div class="item">
          <img class="third-slide" src="/images/TMPstudio.jpg" alt="Third slide" style="width: 600px;">
          <div class="container">
            <div class="carousel-caption">
              <h1>Studio Services</h1>
              <p></p>
              <p><a class="btn btn-lg btn-primary" href="#" role="button">Check-It Out</a></p>
            </div>
          </div>
        </div>
      </div>
      <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
      </a>
    </div><!-- /.carousel -->
      </div>

      <div id="about" class="tab-pane fade">
        <img src="images/entry.jpg" id="AboutPic1">
        <h1></h1>
        <p id="lead">
            Use this document as a way to quickly start any new project.<br> 
            All you get is this text and a mostly barebones HTML document.
        </p>
      </div>

      <div id="services" class="tab-pane fade">
        <h1>Services</h1>
        <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
      </div>

      <div id="portfolio" class="tab-pane fade">
        <h1>Portfolio</h1>
        <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
      </div>

      <div id="contact" class="tab-pane fade">
        <div id="map"></div>
        <div id="contact-content">
        <h1>We're looking forward to<br> 
            hearing from you!</h1><br>
        <h2 style="text-decoration: underline">Phone Number:</h2>
        <h2>edited</h2><br>
        <h2 style="text-decoration: underline">Email:</h2>
        <h2>edited</h2><br>
        <h2 style="text-decoration: underline">Address:</h2>
        <h2>
            edited
        </h2>
        </div>
      </div>

    </div><!-- /.container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="../../dist/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>