gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:04:56 25 4
gpt4 key购买 nike

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

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 作为答案。要解决此问题,您可能需要在比较之前将输入字符串转换为小写。

关于带有 if 语句的 C++ 字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21339750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com