【发布时间】:2018-08-23 02:44:25
【问题描述】:
这是我在这里的第一篇文章。我是 C++ 新手(上周才开始),花了几个小时在这上面,我很难过。
我知道我在这个程序中可能做错了很多事情,但我向你们保证我已经尽力了。验证输入超出了我的作业范围,但我想尝试一下,因为只是获取输入并返回它们很无聊。
基本上,输入验证适用于外部循环,但对于内部循环,即使无效也会失败。
#include <iostream>
using namespace std;
//Global Variables
int cubeLength = 0;
int cubeWidth = 0;
int cubeHeight = 0;
int cubeSurfaceArea = 0;
int cubeVolume = 0;
bool valid = false;
int main() {
//Ask user for cubeLength and validate input for integer values
do {
cout << "Please enter a numerical value for the length of a cube" <<endl;
cin >> cubeLength;
if (cin.good()) {
valid = true;
//Ask user for cubeWidth and validate input for integer values
do {
cout << "Please enter a numerical value for the width of a cube" <<endl;
cin >> cubeWidth;
if (cin.good()) {
valid = true;
//Ask user for cubeHeight and validate input for integer values
do {
cout << "Please enter a numerical value for the height of a cube" <<endl;
cin >> cubeHeight;
if (cin.good()) {
valid = true;
}
else
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Invalid cube height. Please try again" << endl;
}
}while (!valid);
}
else
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Invalid cube width. Please try again" << endl;
}
}while (!valid);
}
else
{
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Invalid cube length. Input is not an integer" << endl;
}
} while (!valid);
//Perform calculations for surface area and volume then assign them to their associated variables
if (cubeLength >= 1 && cubeWidth >= 1 && cubeHeight >= 1)
{
valid = true;
cubeSurfaceArea = ((2*(cubeWidth*cubeLength))+(2*(cubeLength*cubeHeight))+(2*(cubeWidth*cubeHeight)));
cubeVolume = (cubeWidth*cubeLength*cubeHeight);
}
else {
cout << "Sorry, one or more cube inputs is invalid. Ending program. Please restart and try again." << endl;
return 0;
}
//Output surface area and volume to user
cout << "Length = " << cubeLength << " Width = " << cubeWidth << " Height = " << cubeHeight << endl;
cout << "The surface area of your cube is " << cubeSurfaceArea << "." << endl;
cout << "The volume of your cube is " << cubeVolume << "." << endl;
//Pause system and end program
return 0;
}
我在底部添加了用于计算的 if 语句,以防止它在整个程序中一直下降并退出。
我还在本网站和其他网站上检查了很多关于验证整数和循环输入的类似问题,但一直无法弄清楚。我的理论是我要么弄乱了有效的布尔逻辑,要么使用了错误的循环方法。
【问题讨论】:
-
你确定 cin.good() 是你想要做的正确调用吗?文档建议这将检查 cin 流的状态是否存在 EOF 或读/写失败,这听起来不像是要验证流的实际内容......
-
cin.good 在评估时适用于第一个循环,所以作为一个新手,这就是我解决的问题。我可以输入小数和字符串,并且每次都应该是无效的,但是我认为失败是在布尔逻辑中。我也很难找到关于 cin.good 的好的文档,你有什么建议我可以看/应该注意吗?真的很感激。
-
测试实际输入操作一般比较好,比如
if(cin >> foo) ... -
@B00489663 对此有一些参考,cplusplus.com/reference/ios/ios/good 就是其中之一。基本上我不确定编写的代码是否符合您的预期。
标签: c++ loops validation int cin