I am trying to make a basic choose-your-own-adventure style game by developing a basic system by which the program takes user char input and makes a decision using if-else statements to append strings in a certain pattern. In the following program I have tried to use strcat after a set of conditions to yield different output, but my outputs keep failing miserably. Any help someone could offer would be incredible.
#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;
}
CodePudding user response:
When you use the ==
operator to compare C-style strings, you're actually comparing the addresses, not the contents, of the strings, which is not helpful in this case. Try using the strcmp()
library routine instead, and you'll probably get a lot farther with what you're trying to do.
CodePudding user response:
You can't compare the contents of C-style strings using operator==
. You need to use strcmp()
instead:
if (strcmp(answer, "no") == 0)
Also, else (answer== "yes");{
is wrong too. Not only because of the comparison issue, but also because you are missing a required if
, and have an erroneous ;
. It should be else if (strcmp(answer, "yes") == 0){
instead.
That being said, you really should be using std::string
instead of char[]
, eg:
#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;
}
CodePudding user response:
if (answer== "no")
You're comparing the memory address of answer
and the string literal "no"
, so that condition is false
You should use strcmp()
like this:
if(strcmp(answer, "no") == 0)
Also, your else
has the wrong syntax. You should use else if
Change that to:
else if (strcmp(answer, "yes") == 0)
{
std::cout<< strcat(str1,str3);
}
Or even better, throw C-style string out of the window and use std::string
instead.
#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;
}