C++:与有麻烦做while循环

问题描述:

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的循环不断repeating.Can谁能帮助我知道为什么它的发生?C++:与有麻烦做while循环

+1

'account_type!='S'|| 'C''不会做你认为它做的事。将其更改为'account_type!='S'|| account_type!='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,反之亦然,因此循环永远不会结束。

+0

所以&&会像||一样行事。为整数? – Akula

+0

@Akula我将它改为&&的原因是因为代码仍然会随着||而不规则地循环。 &&和||除&&意味着'和'和||之外的整数意味着'或' –

+0

@Akula当你使用||和数字上的&&变成布尔值。如果它不是0,它变成真,如果它变为0,它变成假。 –

你虽然检查是错误的。你必须把它写这样的:

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

您不能执行||检查,或任何像,这一问题时,必须始终重新状态变量。