[英]Getting rid of input buffer
我制作了一个程序,它根据用户输入创建一个矩形。 如果用户输入 8,程序将生成一个 8 x 8 的矩形。 我有制作矩形的所有代码。 但我想要做的是让程序询问用户是否要重新创建另一个矩形,它确实如此,但每次程序要求新输入时,它都会显示之前创建的旧矩形。 不是用户要求创建的新的。 我如何摆脱以前的输入缓冲区以便能够创建一个新的矩形? 谢谢!
#include <iostream>
using namespace std;
int main ()
{
//declaring variables
int size;
char choice;
cout << "**************** Drawing Squares Program ******************************" << endl;
cout << "* Algorithm generates a hollow square, using the character +, - and | *" << endl;
cout << "* Acceptable size dimension: Any value from 3 to 20. Choose carefully.*" << endl;
cout << "***********************************************************************" << endl;
cout << "Side size = ";
cin >> size;
while (size < 3 || size > 21)
{
cout << endl;
cout << "Number is either too big or small. Please rechoose." << endl;
cout << endl;
cout << "Side Size: ";
cin >> size;
}
while (choice != 'n')
{
//the beginning for loop will create one single + in the beginning of the line.
for (int FirstL = 0; FirstL < 1; FirstL++)
{
cout << '+';
//for loop creates the line across the top. It starts at two because we have + on both ends of the line.
for (int straightTop = 2; straightTop < size; straightTop++)
{
cout << "-";
}
cout << "+"; //creates the + at the end of the line. (For top row)
cout << endl;
//this for loop creates the vertical line. It is a nedsted for loop because the for loop has to create two of the same exact vertical lines side by side but with space inbetween them so the line goes across to the other side.
for (int VerticalLine = 2; VerticalLine < size; VerticalLine++)
{
cout << "|";
for (int verticalSpace = 2; verticalSpace < size; verticalSpace++)
{
cout << " "; //creates the space between both vertical lines.
}
cout << "|\n"; //\n is another form of endl;
}
cout << "+"; //creates + at the end of the vertical line
//for loop creates the bottom line.
for (int straightBottom = 2; straightBottom < size; straightBottom++)
{
cout << "-";
}
//creates + at the end of the line.
cout << "+" << endl;
}
cout << "Great! Would you like to play again?: ";
cin >> choice;
if (choice == 'n')
{
cout << "Thanks for playing!" << endl;
}
if (choice == 'y')
{
size = 0;
}
}
return 0;
}
您要求运行循环之外的大小。 所以你的程序流程看起来像
您需要将该尺寸代码移动到循环中。 所以它看起来像:
while (choice != 'n')
{
cout << "Side size = ";
cin >> size;
while (size < 3 || size > 21)
{
cout << endl;
cout << "Number is either too big or small. Please rechoose." << endl;
cout << endl;
cout << "Side Size: ";
cin >> size;
}
// ...
您也永远不会在循环之前初始化choice
。 您需要将其初始化为'y'
。 当您声明它时,这将是最简单的(这也是在声明变量时养成的好习惯):
char choice = 'y';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.