/*
PROGRAM: Ch6_14.cpp
Written by Corey Starbird
This program calculates the balance
owed to a hospital for a patient.
Last modified: 10/28/13
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
// Prototypes for In-patient and Out-patient functions.
double stayTotal (int, double, double, double); // For In-patients
double stayTotal (double, double); // For Out-patients
int main()
{
char patientType; // In-patient (I or i) or Out-patient (O or o)
double rate, // Daily rate for the In-patient stay
servCharge, // Service charge for the stay
medCharge, // Medication charge for the stay
inTotal, // Total for the In-patient stay
outTotal; // Total for the Out-patient stay
int days; // Number of days for the In-patient stay
// Find out if they were an In-patient or an Out-patient
cout << "Welcome, please enter (I) for an In-patient or (O) for an Out-patient:" << endl;
cin >> patientType;
while (patientType != 'I' || 'i' || 'O' || 'o')
{
cout << "Invalid entry. Please enter either (I) for an In-patient or (O) for an Out-patient:" << endl;
cin >> patientType;
}
cout << "FIN";
return 0;
}
嘿,这里是C ++的新手。我正在研究一个项目,但我无法弄清楚为什么patientType
的验证无法正常工作。我首先使用双引号,但意识到这将表示字符串。我将它们改为单引号,我的程序现在将编译并运行,但无论我输入什么,我,我,O,o或其他任何东西都会运行while循环。
我不知道为什么while循环没有检查条件,看到我确实输入了条件中的一个字符,然后转到cout。可能是一个简单的错误,但我提前感谢你。
答案 0 :(得分:0)
你的状况不对。
你很可能想要这个:
while (patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')
你必须使用&&
。 patientType
不是I
,或者i
始终不是真的。patientType !=
此外,您必须对每个要检查的项目使用i
,否则字符o
,O
,bool
将隐式转换为true
({{1}对于他们所有人)。
答案 1 :(得分:0)
while (patientType != 'I' && patientType != 'i' &&
patientType != 'O' && patientType != 'o')
如上所述,条件始终为真,因为OR-ed中的四个表达式中的三个是非零的。
答案 2 :(得分:0)
问题在于这一行
(patientType != 'I' || 'i' || 'O' || 'o')
这不符合你的想法,你想要
(patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')
比较运算符严格地在两个值之间,即左侧和右侧。
C和C ++将任何非零值视为“true”。所以,
(patientType != 'I' || 'i' || 'O' || 'o')
被翻译为
(patientType != 'I') or ('i' is not 0) or ('O' is not 0) or ('o' is not 0)