私はイントロC++コンピュータサイエンスコースの学生です。ここに初めて投稿しました。私たちはちょうどwhileループについて学んだことがありますが、割り当てには必要がありませんが、この割り当てに関する入力検証を試みています。このプログラムは、数字のリストを読み、最初と最後の8つがあるリスト内の位置を把握することを目的としています。したがって、私が4つの数字(1,8,42,8)のリストを持っていれば、最初と最後の8つの位置は2と4です。セットのサイズはユーザーによって決まります。C++の入力検証中にループが終了しない
私はwhileループを作ろうとしていましたが、ユーザが実際に入力したものが実際に数字だったのを確認しましたが、 "。"または "a"ループは無限に進み、終了しません。私は自分の誤りを見つけることができず、私の教科書に書かれているものとまったく同じ構文を使っていると私には分かります。誰かが私のwhileループで間違っていることを私に見せてもらえますか?
int numbers, //How large the set will be
num, //What the user enters for each number
first8position = 0, //The first position in the set that has an 8
last8position = 0; //The last position in the set that has an 8
//Prompt the user to get set size
cout << "How many numbers will be entered? ";
cin >> numbers;
//Loop to get all the numbers of the set and figure out
//which position the first and last 8 are in
for (int position = 1; position <= numbers; position++)
{
cout << "Enter num: ";
cin >> num;
//If num isn't a digit, prompt the user to enter a digit
while (!isdigit(num))
{
cout << "Please enter a decimal number: ";
cin >> num;
}
//If num is 8, and first8position still isn't filled,
//set first8position to the current position.
//Otherwise, set last8position to the current position.
if (num == 8)
{
if (first8position == 0)
first8position = position;
else
last8position = position;
}
}
//If the set had an 8, print what its position was
if (first8position != 0)
cout << "The first 8 was in position " << first8position << endl;
//If there was more than one 8, print the last 8 position.
//Otherwise, the first and last 8 position are the same.
if (last8position != 0)
cout << "The last 8 was in position " << last8position << endl;
else
cout << "The last 8 was in position " << first8position << endl;
//If there were no 8s, say so.
if (first8position == 0)
cout << "Sorry, no eights were entered.";
return 0;
}
関連/デュープhttps://stackoverflow.com/questions/19521320/why-do-i-get-an-infinite-loop-if-i-enter-a-letter-rather-than-a -number – NathanOliver
'std :: isdigit'も正しく使用していません。どのように動作するか見てみる:http://en.cppreference.com/w/cpp/string/byte/isdigit – NathanOliver