Noah Zarc Noah Zarc - 26 days ago 6
C++ Question

"if" and "else if" commands are not working in c++

I am in the process of making a chat bot and i am just experimenting at this point. but my "if" commands are not working and when i enter "moodToday" it just skips right to the else command.

(capitalization of "moodToday" is not the error)

any and all help would be appreciated

#include <fstream>
#include <cmath>
using namespace std;

int main() {

char name[50], moodToday[50];


cout << "A few things you should know at this time..." << endl << "1. I can't process last names." << endl << "2. I can't process acronyms." << endl;
system("pause");
cout << endl << endl << "What is your name?" << endl;
cin >> name;
cout << "Hello " << name << "." << endl << "How are you today?" << endl;
cin >> moodToday;


//can't figure this out...
if ((moodToday == "sad") || (moodToday == "bad") || (moodToday == "horrible")) {
cout << "That's not good." << endl << "Why are you feeling " << moodToday << "today?" << endl;
}
else if (moodToday == "good") {
cout << "Great!" << endl;
}
else {
cout << "I'm sorry, I don't undrestand that feeling." << endl;
}


system("pause");

return 0;

}

Answer

If you're doing C++, then you should be using std::string and not the old C-style buffers.

#include <string>

int main() {
  std::string name, moodToday;
}

C++ strings are significantly better than C strings since they don't have buffer overflow problems and are easily compared with ==.

Also, as a tip, try to avoid using namespace std; since that can cause namespace conflicts. As annoying as it can be to type std:: all the time it does make it clear where that class or template originated from and who's responsible for it code-wise. That way your own classes and templates are obvious.