gpt4 book ai didi

c++ - 验证用户输入为整数 : User has to enter input twice

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:08 25 4
gpt4 key购买 nike

我提示用户输入一个整数值。当值不正确时,程序运行。但是,当用户输入整数时,用户需要输入两次。

我查看了有关如何使用 while 循环捕获错误输入的其他教程,那部分对我有用。但是,需要输入两次整数值才能运行程序。

#include <iostream>
using namespace std;

int main() {
cout << "*************************************************" << endl;
cout << "******************|DVD Library|******************" << endl;
cout << "*************************************************" << endl;
cout << "1.\tAdd DVD" << endl;
cout << "2.\tDelete DVD" << endl;
cout << "3.\tSearch DVD" << endl;
cout << "4.\tList All DVDs in the Library" << endl;
cout << "5.\tAdd DVD to Favorites List" << endl;
cout << "6.\tDelete DVD from Favorites List" << endl;
cout << "7.\tSearch DVD in Favorites List" << endl;
cout << "8.\tList All DVDs in Favorites List" << endl;
cout << "9.\tQuit" << endl;
cout << "*************************************************" << endl;

int input;
cin >> input;
while (!(cin >> input)) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter an integer --> " << flush;
}
if (input < 1 || input > 9) {
cout << "Invalid input! Please try again!" << endl;
}
return 0;
}

最佳答案

你要求输入两次:

cin >> input;
while(!(cin >> input )){

删除第一行可能会如您所愿。

关于c++ - 验证用户输入为整数 : User has to enter input twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56214940/

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