使用 if 语句C++字符串变量

C++ string variables with if statements

本文关键字:字符串 变量 C++ 语句 if 使用      更新时间:2023-10-16

我尝试以各种可能的方式重新定义这些变量 尝试让这条线工作。 我只举一个例子 在这里代表困扰我的事情。

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.

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

若要修复,请删除yesno的声明(不需要它们),并改用字符串文本:

if (input == "yes") {
...
}

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

const string YES = "yes";
const string NO = "no";
const double FRAME_COST = 45.0;

int main()
{
string input;
double frames;
cout << "Hello World" << endl; 
cin >> input;
if(input == YES)
{
cout << "How many?" << endl;
cin >> frames;
frames = frames * FRAME_COST;
cout << frames << endl;
}
return 0;
}

仅仅有一个名为"yes"的char和另一个名为"no"的char是不够的,特别是因为你实际上从未给它们任何值。我想你的意思是写:

if (input == "yes") {

input == yes需要input == "yes"引号让编译器知道它是一个字符串而不是标识符。我也认为这可能会有所帮助。

您需要使用字符串或字符数组进行比较。

if (input == yes)

此行不执行任何操作yes因为 是永远不会初始化的字符指针。 它应该是

if (input == "yes")

而且您不需要yes变量(或者,您可以声明一个带有要检查的值的常量字符串:例如const std::string YES("yes");)

请注意,您可能还应该考虑区分大小写。

此外,您将整数frames乘以双FRAME_COST(大概是为了获得总成本? 这将导致整数值被截断,因为您将其存储在int中。 如果您希望成本以美元和美分为单位,则应将其存储在doublefloat中:

double cost = frames * FRAME_COST;

yesno应该是字符串常量(如果你想使它们与输入完美匹配),要么是const std::string,要么是const char*(或自动),但你必须确定一个值。

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

cout << "Do you want additional frames? Type yes/no:  ";
cin  >> input;
if (input == yes){ // exact comparison (maybe add a space trim of input?)
cout << "How many?"
cin >> frames;
frames = frames * FRAME_COST;
}

有没有办法为一个 if 语句创建多个输入,而不必创建多个 if 语句,而不是只为一个输入创建一个 if 语句?

例如。。。

string input;
cout << "Are you Bob?";
if (input == "yes", "no", "maybe"){
cout << "Sure...";
}else {
cout << "CANNOT COMPUTE";
}

每次我尝试这个时,输入可以是任何东西,它会表现得好像我说"是"、"否"或"也许"。

#include <iostream>
#include<cmath>;
using namespace std;
int main() 
{
double const FRAME_COST = 45.00;
string input;
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;
cout<<frames<<endl;}
else 
{cout<<"please enter yes for additional frames";
}

//ALL ERRORS ARE SOLVED;
//ENJOY
//FOR MORE HELP YOU CAN CONTACT ME WHATSAPP +923034073767.
// 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.
return 0;
}