c++程序故障

C++ Program glitch?

本文关键字:故障 程序 c++      更新时间:2023-10-16

我需要帮助调试我的代码。所以我编写了一个加减数字的程序,但是当我实现一个do-while循环来重播程序时,实际的程序关闭了,不执行do-while循环,也不重播程序。是我的代码有问题吗?

注:我也使用代码块IDE

#include <iostream>
using namespace std;
int main()
{
    // Addition and Subtraction Calculator
    int a_number, number1, number2, sum, number3, number4, subsum, again;
    // subsum = subtracted sum
    // number1 and number2 are variables that hold the users input for addition 
    // number3 and number4 are variables that hold the users input for     subtraction                
    do
    {
        cout << "Addition & Subtraction Calculator" << endl;
        cout << "-------------------------------------------" << endl;
        cout << "1. Addition" << endl;
        cout << "2. Subtraction" << endl;
        cout << "Please enter a number [1 or 2]" << endl;
        cin >> a_number;
        while (a_number < 1 || a_number > 2)
        {
            cout << "Please enter either 1 or 2" << endl;
            cin >> a_number;
        }
        switch (a_number)
        {
        case 1:
            cout << "Please enter a number" << endl;
            cin >> number1;
            cout << "Please enter another number" << endl;
            cin >> number2;
            sum = (number1 + number2);
            cout << "The sum is " << sum << endl;
            break;
        case 2:
            cout << "Please enter a number" << endl;
            cin >> number3;
            cout << "Please enter another number" << endl;
            cin >> number4;
            subsum = (number3 - number4);
            cout << "The answer to the subtraction problem is: " << subsum << endl;
            break;
        }
        cout << "Do you want to try again? [y/n]" << endl;
        cin >> again;
    }
    while (again == 'y' || again == 'n');

    return 0;
}

OK。所以OP在应该用char的地方用了int。这就涵盖了眼前的问题。int again应为char again

但是其他答案都忽略了重要的一点。

int again;
cin >> again;

用户输入将按照again的要求转换为整数。输入y或n无法转换为整数,因为y和n都不是数字,无法转换。again保持不变,保持内存中的垃圾值,实际上可能是y或n,但更重要的是cin现在处于错误状态,需要在继续之前清除。

cin会通知OP,如果它已经被测试了。我们来测试一下

int again;
if (cin >> again)
{
     // got good input. Do something with it.
}
else
{
     // got bad input. 
     cin.clear();
     // that bad input is still in the buffer and needs to be removed
     cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
     // the above line will wipe out everything to the end of the stream or 
     // end of line, whichever comes first. 
}

为什么这很重要:因为OP正在使用cin进行大量数字输入,并且没有检查其有效性。例如:

cout << "Please enter a number [1 or 2]" << endl;
cin >> a_number;

如果用户输入了除数字以外的任何内容,程序将完全中断,并且在没有kill信号的情况下无法退出。

总是检查错误状态和返回代码。他们是来帮忙的。在使用用户输入之前,始终对其进行验证。用户是邪恶的,他们会试图破坏你的程序。别让他们。

char again;代替int again;

在你的代码againint,当在(again == 'y' || again == 'n')你比较again(一个int)与char,这是没有意义的

需要将again变量更改为char数据类型,因为需要存储文本。像这样:

char again;

您还需要将while语句更改为:

while(again != "n");

while(again == "y");