![](/img/trans.png)
[英]How can use my if-else statements to take a specific action based on the input of the user's weight and then display it to the console?
[英]How can I use strcat() within an if-else statement to change based on a user inputs "yes" or "no"?
我试图通过开发一个基本系统来制作一个基本的选择你自己的冒险风格的游戏,程序通过该系统接收用户字符输入并使用 if-else 语句做出决定以按特定模式附加字符串。 在下面的程序中,我尝试在一组条件之后使用 strcat 来产生不同的输出,但是我的输出一直失败得很惨。 有人能提供的任何帮助都是不可思议的。
#include <iostream>
#include<cstring>
#include<string>
#include<iomanip>
#include<ios>
#include<limits>
using namespace std;
int main()
{
char str1[50]= "F*ck";
char str2[50]= "You";
char str3[50]= "Me";
char answer[50];
cout<< "Do you like rock music yes or no?";
cin>> answer;
if (answer== "no"){
cout<< strcat(str1,str2);
} else (answer== "yes");{
cout<< strcat(str1,str3);
}
return 0;
}
当您使用==
运算符来比较 C 风格的字符串时,您实际上是在比较字符串的地址,而不是内容,这在这种情况下没有帮助。 尝试改用strcmp()
库例程,您可能会在尝试做的事情上走得更远。
您无法使用operator==
比较 C 样式字符串的内容。 您需要改用strcmp()
:
if (strcmp(answer, "no") == 0)
另外, else (answer== "yes");{
也是错误的。 不仅是因为比较问题,还因为您缺少一个必需的if
,并且有一个错误的;
. 应该是else if (strcmp(answer, "yes") == 0){
代替。
话虽如此,您确实应该使用std::string
而不是char[]
,例如:
#include <iostream>
#include <string>
using namespace std;
int main() {
const string str1 = "F*ck";
const string str2 = "You";
const string str3 = "Me";
string answer;
cout << "Do you like rock music yes or no?";
cin >> answer;
if (answer == "no"){
cout << str1 << str2;
} else if (answer == "yes"){
cout << str1 << str3;
}
return 0;
}
if (answer== "no")
您正在比较answer
的内存地址和字符串文字"no"
,因此该条件为false
你应该像这样使用strcmp()
:
if(strcmp(answer, "no") == 0)
另外,您的else
语法错误。 你应该使用else if
将其更改为:
else if (strcmp(answer, "yes") == 0)
{
std::cout<< strcat(str1,str3);
}
或者更好的是,将 C 风格的字符串抛出窗口并使用std::string
代替。
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
#include <ios>
#include <limits>
// using namespace std; is bad
int main()
{
std::string str1{"F*ck"};
std::string str2{"You"};
std::string str3{"Me"};
std::string answer;
std::cout<< "Do you like rock music yes or no?";
std::cin>> answer;
if (answer == "no")
{
std::cout<< (str1 + str2);
}
else if(answer == "yes")
{
std::cout << (str1 + str3);
}
return 0;
}
谢谢大家的帮助,我能够重写程序,现在它可以工作了。 对于基于文本的选择你自己的冒险游戏真的很有帮助。 新计划如下:
#include <iostream>
#include<cstring>
#include<string>
using namespace std;
int main() {
char str1[50]= "F*ck";
char str2[50]= " You";
char str3[50]= " Me";
char answer[50];
cout<< "Do you like rock music (yes or no)?"<<endl;
cin>> answer;
if (strcasecmp(answer,"no") == 0){
cout<< strcat(str1,str2)<<endl;
} else if (strcasecmp(answer,"yes") == 0){
cout<< strcat(str1,str3)<<endl;
} else {
cout<< strcat(str1," off")<<endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.