C ++字符串变量和if语句 [英] C++ string variables with if statements
问题描述
我试过以每一种可能的方式重新定义这些变量
尝试得到这行代码。我只是给一个例子
这里代表什么困扰我。
I've tried re-defining these variables in every imaginable way possible to try and get this line to work. I'm just going to give one example here to represent what's troubling me.
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.
推荐答案
您当前的程序有未定义的行为,因为是
和没有
是尚未初始化的字符变量,并且您正在使用其中一个进行比较。
Your current program has undefined behavior, because yes
and no
are character variables that have not been initialized, and you are using one of them in a comparison.
要修复,删除 yes
和 no
的声明不需要它们),并使用字符串字面量:
To fix, remove the declarations of yes
and no
(you do not need them), and use a string literal instead:
if (input == "yes") {
...
}
注意:您的比较可能过于严格, -敏感。它将需要一个是
,但它不会采取是
或是
作为答案。要解决这个问题,您可能需要在比较之前将输入字符串转换为小写。
Note: your comparison may be too strict, because it is case-sensitive. It will take a yes
, but it would not take a Yes
or a YES
as an answer. To address this you may want to convert the input string to lower case before the comparison.
这篇关于C ++字符串变量和if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!