1
 /*
 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无法正常工作。我首先有双引号,但意识到这将表示字符串。我将它们更改为单引号,我的程序现在将编译并运行,但是无论我输入什么,I,i,O,o 或其他任何内容,while 循环都会运行。

我不知道为什么 while 循环不检查条件,看到我确实输入了条件中的一个字符,然后继续进行 cout。可能是一个简单的错误,但我提前谢谢你。

4

3 回答 3

0

你的 while 条件是错误的。

你很可能想要这个:

while (patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')

你必须使用&&. patientTypeis not Ior it is noti总是正确的。此外,您必须patientType !=对每个被检查的项目使用,否则字符i, o,O将被隐式转换为bool(true对于所有这些项目)。

于 2013-11-01T03:53:10.717 回答
0
while (patientType != 'I' && patientType != 'i' &&
       patientType != 'O' && patientType != 'o')

如所写,条件始终为真,因为四个表达式中的三个 OR-ed 一起是非零的。

于 2013-11-01T03:53:12.677 回答
0

问题是这条线

(patientType != 'I' || 'i' || 'O' || 'o')

这不是你想的,你想要的

(patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')

比较运算符严格在两个值之间,左侧和右侧。

C 和 C++ 将任何非零值视为“真”。所以,

(patientType != 'I' || 'i' || 'O' || 'o')

被翻译为

(patientType != 'I') or ('i' is not 0) or ('O' is not 0) or ('o' is not 0)
于 2013-11-01T03:53:59.120 回答