C++ 初学者输入错误数据类型时的无限循环并帮助评估我的代码

标签 c++ function variable-assignment evaluation

我的任务是创建一个基于菜单的程序,以使用用户定义的函数计算多个形状的面积。当用户输入字符而不是数字时,我的代码会创建无限循环。我应该怎么办?另外,我想如果有人可以评估我的代码,我应该更改或修改什么吗?我还是 C++ 新手。

输入: 1. 一个 2.j

#include <iostream>
#include <cmath>
using namespace std;

float Circle(double r1);
float Rectangle(double length, double width);
float Triangle(float s1, float s2, float s3);
float Cylinder(double height, double r2);
float Square(double l1, double l2);

int main()
{  
    char o, d;
    do
    {//List  of what shapes the program can calculate
        cout << " Calculator for area of shapes " << endl;
        cout << endl;
        cout << " List of Area: " << endl;
        cout << " A. Circle " << endl;
        cout << " B. Rectangle " << endl;
        cout << " C. Triangle " << endl;
        cout << " D. Cylinder " << endl;
        cout << " E. Square " << endl;
        cout << " X. Exit " << endl;
        cout << endl;
        //Choose what shape to calculate
        cout << " Please enter the area you wish to calculate: ";
        cin >> o;
        cout << endl;
        //Program determine what calculation to use
        switch (o)
        {
        case 'a'://For Circle
        case 'A':

            double r1;
            while (true)
            {
                cout << " Radius of Circle: ";
                cin >> r1;
                if (r1 > 0)
                {
                    Circle(r1);
                    cout << endl;
                    break;
                }
                else
                {// If the input is less than 0 an error message will occur and user need to reinput the data
                    cout << " ERROR! NOT A CIRCLE. Please input value more than 0." << endl;
                }
            }
            break;

        case 'b'://For Rectangle
        case 'B':
            double length, width;
            while (true)
            {
                cout << " Length of Rectangle: ";
                cin >> length;
                cout << " Width of Rectangle: ";
                cin >> width;
                if (length > 0 && width > 0)
                {
                    Rectangle(length, width);
                    cout << endl;
                    break;
                }
                else
                {
                    cout << " ERROR! Not A Rectangle. Please input value more than 0 " << endl;
                }
            }

        case 'c'://For Triangle
        case 'C':
            float s1, s2, s3;
            while (true)
            {
                cout << " Length of side A: ";
                cin >> s1;
                cout << " Length of side B: ";
                cin >> s2;
                cout << " Length of side C: ";
                cin >> s3;
                if ((s1 + s2) > s3 && (s2 + s3) > s1 && (s3 + s1) > s2)
                {
                    Triangle(s1, s2, s3);
                    cout << endl;
                    break;
                }
                else
                {
                    cout << " ERROR!!! NOT A TRIANGLE. Please input value more than 0 " << endl;
                }
            }

        case 'd'://For Cylinder
        case 'D':
            double height, r2;
            cout << " Radius of Cylinder: ";
            cin >> r2;
            cout << "Height of Cylinder: ";
            cin >> height;
            while (true)
            {
                if (r2 > 0 && height > 0)
                {
                    Cylinder(height, r2);
                    break;
                }
                else
                {
                    cout << " ERROR!!! NOT A CYLINDER. Please input value more than 0 " << endl;
                }
            }

        case 'e'://For Square
        case 'E':
            double l1, l2;
            while (true)
            {
                cout << " Length of side 1: ";
                cin >> l1;
                cout << " Length of side 2: ";
                cin >> l2;
                if (l1 > 0 && l2 > 0)
                {
                    Square(l1, l2);
                    break;
                }
                else
                {
                    cout << " ERROR!!! NOT A SQUARE. " << endl;
                }
            }

        case 'x':
        case 'X'://Program end
            cout << " ---- PROGRAM END ---- ";
            exit(0);

        default: // Error message occur if user don't
            cout << " ERROR!! PLEASE INPUT RIGHT LETTER ";
            cout << endl;
        }
        // user can choose to use program again or not
        cout << " Do you wish to continue using the calculator?(Y/N): ";
        cin >> d;
        cout << endl;

    } while (d == 'y' || d == 'Y');
        if (d == 'n' || d == 'N')
        {
            cout << " ---- PROGRAM END ---- ";
        }

    return 0; 
}
float Circle(double r1)//Calculation for Circle
{
    double area;
    const double pi = 3.14; 
    area = pi * (r1 * r1); //Formula for area of Circle
    cout << " Area of Circle: " << area; 
    cout << endl;
    return 0;
}
float Rectangle(double length, double width)//Calculation for Rectangle
{
    double area;
    area = length * width;//Formula for area of Rectangle
    cout << " Area of Rectangle: " << area;
    cout << endl;
    return 0;
}
float Triangle(float s1, float s2, float s3)//Calculation for Triangle
{
    float area, s;
    s = (s1 + s2 + s3) / 2;
    area = sqrt(s * (s - s1) * (s - s2) * (s - s3));//Formula for area of Triangle
    cout << " Area of triangle: " << area << endl;
    cout << endl;
    return 0;
}
float Cylinder(double height, double r2)//Calculation for Cylinder
{
    double area; 
    const double pi = 3.14;
    area = 2 * pi * r2 * (r2 + height);//Formula for area of Cylinder
    cout << endl;
    return 0;
}
float Square(double l1, double l2)//Calculation for Square
{
    double area;
    area = l1 * l2;//Formula for area of Square
    cout << " Area of Square: " << area << endl;
    cout << endl;
    return 0;
}

最佳答案

float r1; cin >> r1; 和非数字输入,输入不会消耗任何内容。重复 cin >> r1 会导致无限循环。

要做什么?

  1. 检查 cin >> r1 是否成功: if (cin >> r1) {/* process r1 */}
  2. 如果不成功,请执行某些操作来处理错误的输入: else { cin.clear(); cin.ignore(); }

std::ios::clear()

Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.

std::istream::ignore()

Extracts and discards characters from the input stream until and including delim.

示例:

#include <iostream>
#include <limits>

int main()
{
  double value = 0.0;
  for (;;) {
    std::cout << "Value: ";
    if (std::cin >> value) {
      break; // success -> bail out of loop
    } else {
      std::cerr << "Wrong input!\n";
      std::cin.clear(); // reset state
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // consume wrong input
    }
  }
  std::cout << "Value: " << value << '\n';
  return 0;
}

输出:

Value: <b>Hello</b><kbd>↵</kbd>
Wrong input!
Value: <b>1.23</b><kbd>↵</kbd>
Value: 1.23

Live Demo on coliru

关于C++ 初学者输入错误数据类型时的无限循环并帮助评估我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52905901/

相关文章:

Javascript循环创建函数并使用收到的基于PHP查询的id附加值

sql - 使用 SELECT 的 SQL Server 变量赋值中的执行顺序

java - Groovy 变量的作用域、赋值和引用

java - Java 中的合并数组赋值

c++ - 使用 for_each 调用成员函数

C 函数之间的清晰性

javascript - 从字符串的一部分中删除文本

c++ - Visual Studio __VA_ARGS__ 问题

c++ - 从 C++ 转换为 C

c++ - Visual C++ 2008 Boost 问题