带有if语句的C++字符串变量

jud*_*omi 1 c++ string if-statement

我已经尝试以各种可能的方式重新定义这些变量,以尝试让这条线工作.我将在这里举一个例子来表示令我不安的问题.

double const FRAME_COST = 45.00;
string input;
char yes,
     no;
int frames;


cout << "Do you want additional frames? Type yes/no:  ";
cin  >> input;

    if (input == yes){
       cout << "How many?"
       cin >> frames;
       frames = frames * FRAME_COST;
       }

// The problem is in **the if statement**
// I need to use a string not a bool (according to my professor)
// I can't get the compiler to recognize the **if statement**
// I realize this isn't practical, but he always throws curve balls.
Run Code Online (Sandbox Code Playgroud)

das*_*ght 10

您当前的程序具有未定义的行为,因为yes并且no是尚未初始化的字符变量,并且您在比较中使用其中一个.

要修复,删除yesno(您不需要它们)的声明,并使用字符串文字:

if (input == "yes") {
    ...
}
Run Code Online (Sandbox Code Playgroud)

注意:您的比较可能过于严格,因为它区分大小写.它需要一个yes,但它不会采取YesYES作为答案.要解决此问题,您可能希望在比较之前将输入字符串转换为小写.