c++: do while循环出现问题

C++: Having troubles with do while loop

本文关键字:问题 循环 while do c++      更新时间:2023-10-16
do {
    cout << "Enter the account type (C for current and S for savings): ";
    cin >> account_type;
} while (account_type != 'S' || 'C');

我有account_type设置为char,问题是,每次我运行程序,我输入S或C循环不断重复。有人能告诉我为什么会这样吗?

c++中所有非零值在布尔运算中计算为true。所以account_type != 'S' || 'C'等于account_type != 'S' || true。这意味着你的循环永远不会退出。

您需要做的是执行两个检查

do {
    cout << "Enter the account type (C for current and S for savings): ";
    cin >> account_type;
} while (account_type != 'S' && account_type != 'C');

这是因为你不能说'S' || 'C',你会认为c++会认为你的意思是,如果account_type是S或C,然而c++在两个单独的部分中看到这一点:(account_type == 'S') || ('C')。('C')将默认为true,因此循环将永远循环下去。

你需要写的是:

do {
    cout << "Enter the account type (C for current and S for savings): ";
    cin >> account_type;
} while (account_type != 'S' && account_type != 'C');

你需要把||改成&&因为如果account_type是S,那么它就不能是C,反之亦然,因此循环永远不会结束。

您的while检查错误。你必须这样写:

while (account_type != 'S' || account_type != 'C')

你不能执行||检查,或者任何类似的事情,你必须总是重新声明变量