返回

C++返回两个数字输入的误差,如果不是整数

发布时间:2022-04-15 12:52:23 299
# golang# c++

我试图让程序返回一个错误,如果用户输入字符/字符串到num1,num2,然后取而代之的是正确的输入

我在网上搜索,找到了cin的解决方案。fail()但它只对第一个数字有效,或者根本不起作用

有人建议我先找出变量的类型,然后再进行比较,但我搞不清楚

如果没有函数而没有循环,如何以最简单的方式进行验证?

#include 
#include 
using namespace std;

int main () {

    int num1, num2; // two integers
    int choice; // chosen integers
    int ch1 = 0, ch2 = 0,ch3 = 0,ch4 = 0,ch5 = 0; // to keep track of chosen functions
    
    //const for choice of menu
    const int addition = 1,
              substruction = 2,
              multiplication = 3,
              division = 4, 
              modulo = 5,
              numberChange = 6;


    
    //intro
    cout << "This program has been made for arithmetic operations.\n";
    cout << "Please choose two  integers for arithmetic operations\n";
    cin >> num1 >> num2;


    do {
        cout << "Choose number of the operation you want to do\n";
        cout << "1. addition\n";
        cout << "2. subtraction\n";
        cout << "3. multiplication\n";
        cout << "4. division\n";
        cout << "5. modulo\n";
        cout << "6. CHANGE OF NUMBERS\n";
        cout << "To exit menu enter -1!\n";
        cin >> choice;

       

        switch (choice) {
            case 1:
            cout << "Result: " <> num1 >> num2;
            break;
            case -1:

            ofstream myfile ("/Users/margaritakholostova/Desktop/us.txt");
            if (myfile.is_open())
             {
              myfile << "Addition was selected " << ch1 << " times\n";
              myfile << "Subtraction was selected " << ch2 << " times\n";
              myfile << "Multiplication was selected " << ch3 << " times\n";
              myfile << "Division was selected " << ch4 << " times\n";
              myfile << "Modulo was selected " << ch5 << " times\n";
              myfile.close();
            }
            else cout << "Unable to open file";
            return 0; 
            break;
        }

        //return error if input is not integer
        if (cin.fail()) {
            cout << "Error! Please put only integers!" << endl;
            cin.clear();
            cin.ignore(256, '\n');
            cin >> choice;
        }


        // validate the input for right number

        while (choice < addition || choice > numberChange )
        {
            if (choice != -1) {
                cout << "Please choose valid option out of menu (1-5)\n";
                cin >> choice;
            }
            
        }

    } while (choice != -1);        
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(2)
按点赞数排序
用户头像