简体   繁体   English

在C ++中使用两个char变量评估布尔值

[英]Evaluating boolean with two char variables in c++

Apologies, a bit of a beginner here: 抱歉,这里有点初学者:

I'm working on a practice program to determine cost of a long distance call based on hour of the day and day of the week...and I've gotten to my do-while loop and am attempting to use nested branches to split up weekdays with the weekend. 我正在开发一个练习程序,用于根据一天中的某天和一周中的某天确定长途电话的费用...而且我进入了do-while循环,并尝试使用嵌套分支来拆分平日和周末。

However, when I compile and run, both the if and else if nested statements are skipped no matter if I put in the Chars corresponding to the booleans I'm attempting to evaluate. 但是,当我编译并运行时,无论是否插入与要评估的布尔值相对应的Chars,都会同时跳过if和else if嵌套语句。 I'm struggling to understand what I'm missing here. 我正在努力了解我在这里缺少什么。 The instructions clearly state that the days of the week should be stored in two char variables: Mo Tu We Th Fr Sa Su. 指令明确指出,星期几应存储在两个char变量中:Mo Tu We Th Fr Sa Su。

do
{
    //have user input day of week of call
    printf("\nOn what day was the call made? (Mo, Tu, We, Th, Fr, Sa, or Su) ");
    scanf("%c%c", &day1, &day2);

    //branch for weekday vs weekend vs invalid input
    if (((day1 == 'M') && (day2 == 'o')) || ((day1 == 'T') && (day2 == 'u')) || ((day1 == 'W') && (day2 == 'e')) || ((day1 == 'T') && (day2 == 'h')) || ((day1 == 'F') && (day2 == 'r')))
    {
        //determine if phone call was made at hi or low rate times
        printf("At what time was your call made? (HH MM - with 08 00 representing 8:00 AM and 18 30 representing 6:30 PM) ");
        scanf("%f %f", &call_time_hour, &call_time_minute);
        call_time_hour = call_time_hour + (call_time_minute / 60);

        printf("%f", call_time_hour);
    }
    else if (((day1 == 'S') && (day2 == 'a')) || ((day1 == 'S') && (day2 == 'u')))
    {
        printf("What was the duration of your call? ");
        scanf("%d", &call_duration);

        //calculate total cost of call
        cost_of_call = call_duration * 0.15;

        printf("%s %.2lf", "The cost of this call was $", cost_of_call);
    }
    calls_made--;
    printf("%d", calls_made);
}while (calls_made > 0);

So, for example, when I compile and run the program and enter "Sa" as the day that the call was made, it then moved directly to the 'calls_made--' step. 因此,例如,当我编译并运行该程序并在发出呼叫的日期输入“ Sa”时,它随后直接移至“ calls_made--”步骤。

The problem is because previous scanf . 问题是因为先前的scanf Debug and look what characters are really scanned. 调试并查看真正扫描了哪些字符。 I'm sure that day1 would be '\\n' . 我确定day1将是'\\n'

In this case clear the input stream before scanning the day of week: 在这种情况下,请在扫描星期几之前清除输入流:

while (getchar() != '\n');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM