2011-05-27 108 views
0

如果用户选择1或2,则函数不会运行。有什么建议么?C++控制台不显示菜单

#include <iostream> 
using namespace std; 

void getTitle(); 
void getIsbn(); 

int main() 
{ 
    int choice = 0;  // Stores user's menu choice 

    do 
    { 
     // Display menu 
     cout << "    Main Menu\n\n\n"; 

     // Display menu items 
     cout << " 1. Choose 1 to enter Title.\n"; 
     cout << " 2. Choose 2 to enter ISBN.\n"; 
     cout << " 3. Choose 3 to exit.\n"; 

     // Display prompt and get user's choice 
     cout << " Enter your choice: "; 
     cin >> choice; 

     // Validate user's entry 
     while (choice < 1 || choice > 3) 
     { 
      cout << "\n Please enter a number in the range 1 - 3. "; 
      cin >> choice; 
     } 

     switch (choice) 
     { 
     case 1: 
      getTitle(); 
      break; 
     case 2: 
      getIsbn(); 
      break; 
     } 
    } while (choice != 3); 

    return 0; 
} 

void getTitle() 
{ 
    string title; 
    cout << "\nEnter a title: "; 
    getline(cin, title); 
    cout << "\nTitle is " << title << "\n\n\n"; 
} 

void getIsbn() 
{ 
    string isbn; 
    cout << "\nEnter an ISBN: "; 
    getline(cin, isbn); 
    cout << "\nISBN is " << isbn << "\n\n\n"; 
} 
+0

Mhhh,你确定cin将int读为int吗?因为如果它将它读作一个字符串,也许选择内的“数字”是超出范围的东西。另一件事,当你把1或2放进去的时候,你注意到如果程序超出了内部的范围吗? – 2011-05-27 02:28:32

回答

3

该函数当然应该被调用。但是,会发生什么情况是,按Enter键生成的换行符将返回getline(),并且该函数将返回而没有真正提示您。您需要清除该换行符。您可以使用ignore()来执行此操作:在choice中读取后立即添加cin.ignore();以忽略该一个字符。