C++控制台不显示菜单

C++ console not showing menu

本文关键字:菜单 显示 控制台 C++      更新时间:2023-10-16

如果用户选择1或2,则函数不会运行。有什么建议吗?

#include <iostream>
using namespace std;
void getTitle();
void getIsbn();
int main()
{
    int choice = 0;      // Stores user's menu choice
    do
    {
        // Display menu
        cout << "             Main Menunnn";
        // 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 << "nnn";
}
void getIsbn()
{
    string isbn;
    cout << "nEnter an ISBN: ";
    getline(cin, isbn);
    cout << "nISBN is " << isbn << "nnn";
}

函数当然应该被调用。然而,会发生的情况是,当您按"Enter"键入数字时生成的换行符将由getline()返回,并且该函数将在没有真正提示的情况下返回。你需要清除换行符。您可以使用ignore()来做到这一点:在读取choice后立即添加cin.ignore();以忽略一个字符。