[英]How do I check a valid user input?
我正在為一個在線課程做一個項目,最后一個項目是制作一個“構建你的冒險”程序,用戶可以在其中選擇並導致結局。 我刪除了巨大的介紹,剛剛復制了我有第一選擇的部分。 所以基本上,當我不寫有效數字時,這一切都有效,但是當我寫信時……整個程序開始一個無限循環。 請幫助:這是代碼:
#include <iostream>
int main() {
int c1;
std::cout << "After what felt like thirty minutes of "
"walking you reached a wall. Yes, a wall.\n"
"A wall so tall and wide you couldn't imagine "
"climbing over it or walking around it.\n";
std::cout << "Luckly, you see two animals willing to help you.\n"
"1) A mole that can build a tunnel under the wall\n"
"2) An eagle that can carry you over the wall\n";
std::cout << "Enter 1 or 2 to make a choice: ";
std::cin >> c1;
while (!(std::cin >> c1) || c) {
std::cout << "Error! Please enter a valid input!\n";
std::cout << "Enter 1 or 2 to make a choice: ";
std::cin >> c1;
std::cout << "\n"
}
當您為int
輸入無效輸入時,stream 進入失敗的 state 並且無法讀取更多輸入。 因此,您必須清除 stream 的錯誤 state 並忽略輸入 stream 中剩余的任何內容。
#include <iostream>
#include <limits>
int main() {
int c1;
while (true)
{
std::cout << "Enter 1 or 2 to make a choice: ";
if ((std::cin >> c1) && (c1 == 1 || c1 == 2)) break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Error! Please enter a valid input!\n";
}
// Now c1 is either 1 or 2
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.