输入错误的数据类型并帮助评估我的代码时的C ++初学者无限循环 [英] C++ Beginner Infinite Loop When Input Wrong Data Type and Help Evaluate My Code

查看:76
本文介绍了输入错误的数据类型并帮助评估我的代码时的C ++初学者无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an assignment to create a menu-based program to calculate area of several shapes using user-defined function. My code creates an infinite loop when a user input a char instead of a number. What should I do? Also, I would like if someone could evaluate my code, Is there anything I should change or modify? I'm still new to C++.

输入: 1. a 2. j

Input: 1. a 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会导致无限循环.

With float r1; cin >> r1; and non-numeric input, there is nothing consumed from input. Repeating cin >> r1 results in an endless loop.

该怎么办?

  1. 检查cin >> r1是否成功:if (cin >> r1) { /* process r1 */ }
  2. 如果未成功,请执行一些操作以消耗错误的输入:else { cin.clear(); cin.ignore(); }
  1. Check whether cin >> r1 was successful: if (cin >> r1) { /* process r1 */ }
  2. If not successful, do something to consume wrong input: else { cin.clear(); cin.ignore(); }

std::ios::clear()

通过为其分配状态值来设置流错误状态标志.默认情况下,分配std :: ios_base :: goodbit可以清除所有错误状态标志.

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()

从输入流中提取并丢弃字符,直到包括delim.

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: Hello
Wrong input!
Value: 1.23
Value: 1.23

在大肠杆菌上进行实时演示

这篇关于输入错误的数据类型并帮助评估我的代码时的C ++初学者无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆