gpt4 book ai didi

C++ 控制台不显示菜单

转载 作者:行者123 更新时间:2023-11-28 01:05:56 24 4
gpt4 key购买 nike

如果用户选择 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 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";
}

最佳答案

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

关于C++ 控制台不显示菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com