使用char来确定输出是行不通的

Utilizing char to determine output isnt working

本文关键字:行不通 输出 char 使用      更新时间:2023-10-16

我试图使它,所以当用户输入r或p时,不同的部分将执行,但由于某种原因,它不识别单个字符输入。它只是带我到第一个if语句说我没有正确的值,然后执行r不管我输入什么。为什么这对我不起作用?我尝试了字母本身和对应字母的ascii码,每次它都做同样的事情。它甚至没有输出最后的语句,说无效的服务代码,重试。我的程序是这样的。提前感谢您的时间!

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    char servicetype;
    int account;
    double minutes;
    double initialCharge;
    double overCharge;
    double day;
    double night;
    double dayrate;
    double nightrate;
    double balance;
    string service;
    cout << "Please enter your account number: ";
    cin >> account;
    cout << endl;
    cout << "Please enter your service code: ";
    cin >> servicetype;
    cout << endl;
    if (servicetype != 'r' || 'R' || 'p' || 'P')
    {
        cout << "Invalid service code entered. Please enter a valid service code of P for premium service or R for regular service: ";
        cin >> servicetype;
        cout << endl;
    }
    else if (servicetype == 'r' || 'R')
    {
        service = "regular";
        initialCharge = 10.00;
        overCharge = .2;
        cout << "Please enter the number of minutes the service was used: ";
        cin >> minutes;
        cout << endl;
        balance = initialCharge + (minutes * overCharge);
        cout << "Account number " << account << " with the " << service << " service which was utilized for " << minutes << " minutes and therefore a balance is due of $" << fixed << setprecision(2) << balance << endl;
    }
    else if (servicetype == 'p' || 'P')
    {
        service = "premium";
        initialCharge = 25.00;
        cout << "Please enter the number of minutes which were used between the hours of 6:00 am and 6:00 pm: ";
        cin >> day;
        cout << endl;
        cout << "Please eneter the number of minutes which were used between the hours of 6:00 pm and 6:00 am: ";
        cin >> night;
        cout << endl;
        if (day < 75)
            dayrate = 0;
        else
            dayrate = (day - 75) * .1;
        if (night < 100)
            nightrate = 0;
        else
            nightrate = (night - 100) * .05;
            balance = initialCharge + nightrate + dayrate;
            minutes = day + night;
            cout << "Account number " << account << " with the " << service << " service which was utilized for " << minutes << " minutes and therefore a balance is due of $" << fixed << setprecision(2) << balance << endl;
    }
    else
        cout << "An invalid service code was entered, please try again." << endl;

    system("pause");
    return 0;
}

您需要将serviceType与每个字母进行比较。事实上,你基本上是在说:

"如果serviceType不是'r'或'r'…等",它的计算结果总是true,因为'R'(转换成它的数字等价物)的计算结果是true。它类似于说:

if ('R')
{
}

你可以通过比较serviceType和每个字符来修复它:

if (serviceType != 'r' && serviceType != 'R' && serviceType != 'p' && serviceType != 'P')
{
}

您可以使用tolower(或toupper)来稍微简化它:

if (tolower(serviceType) != 'r' && tolower(serviceType) != 'p')
{
}