当我尝试使用do while时,如果我在第二轮输入一个字符,下面的程序将陷入无限循环。 我不知道为什么,你能给我解释一下吗?
我继续使用它
Visual Studio版本11.0.61219.00更新5
//============================================================
//Do while infinity loop
//============================================================
#include <iostream>
using namespace std;
int main ()
{
int n;
do{
cout << "#####Enter the number you need check#####" << endl;
cin >> n;
if (n != 0 && n <= 10)
cout << "You entered " << n << endl;
cout << "Enter 0 if you want to exit loop" << endl;
if (n > 10)
{
cout << "Sorry with the number " << n << " the result is too big that why i can show you" << endl;
}
}
while( n != 0); // do chi check n khac' 0 nen khi da chay 1 vong` do while luc này n da duoc gan' gia tri tu` vong` lap truoc -> vong` sau input sai gia tri vi' du character 'y' -> code se khong input duoc gia tri moi' vao ->dung` gia tri cu -> infinity
{
cout << "You entered number 0 then bye" << endl;
}
system("pause");
return 0;
}
输入
10
y
输出
10
You entered 10
Enter 0 if you want to exit loop
#####Enter the number you need check#####
y
You entered 10
Enter 0 if you want to exit loop
#####Enter the number you need check#####
10
You entered 10
Enter 0 if you want to exit loop
#####Enter the number you need check#####
10
You entered 10
Enter 0 if you want to exit loop
#####Enter the number you need check#####
答案 0 :(得分:0)
#include "stdafx.h"
#include <iostream>
using namespace std;
//============================================================
//Do while infinity loop
//============================================================
int main()
{
int n;
do {
cout << "#####Enter the number you need check#####" << endl;
cin >> n;
if (!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
}else {
if (n != 0 && n <= 10) {
cout << "You entered " << n << endl;
}
if (n > 10)
{
cout << "Sorry with the number " << n << " the result is too big that why i can show you" << endl;
}
cout << "Enter 0 if you want to exit loop" << endl;// day la mot dong cac ban da comment bang tieng viet
}
}while(n != 0);
{
cout << "You entered number 0 then bye" << endl;
}
system("pause");
return 0;
}
尝试一下。
我不完全知道您的错误是什么。可能是因为您试图将一个非整数变量分配给一个导致内存溢出的整数。因此,在执行其他任务之前请先检查输入的数字