Cubed
Cubed

Reputation: 35

String and Bool (Int Condition to be false) C++

Im new to C++ and I tried searching but I have no idea on what to search. Sorry. My problem is:

  1. When I set the bool condition false, it still requires me to input 2 x to terminate the compiler. Why is that so? (I tried using cin.fail () but it didnt work)

  2. When I print the list of courses, it lists the one that should terminate the program (ie when you press x). How do I correct this? Thank you for your help.

     int main(void)
    {
    // Gather list of courses and their codes from user,
    // storing data as a vector of strings
    const string DegreeCode("PHYS");
    string CourseTitle;
    int CourseCode(0);
    vector <string> CourseList;
    vector <string> :: iterator iter;
    
      bool not_finished(true);
     do
    {
    if (CourseTitle == "x" && "X")
    {
        not_finished=false;
    }
    else
    {
        cout<<"Please enter a course code and a course title (or x to finish): "<<endl;
        cin>>CourseCode;
        cin.sync();
        cin.clear();
        getline(cin , CourseTitle);
    
        ostringstream oss;
        string outputCourseList (oss.str ());
    
        oss  << DegreeCode << " " << CourseCode << " "<< CourseTitle;
    
    
    
        CourseList.push_back (oss.str ());
        cout <<outputCourseList <<endl;
        oss.str("");    //clear oss content
    }
    
      } while(not_finished);
    
          // Print out full list of courses
            cout<<"List of courses:\n"<<endl;
           for (iter = CourseList.begin(); iter != CourseList.end(); iter++)
            cout<<(*iter)<<endl;
    
             return 0;
                }
    

Upvotes: 1

Views: 97

Answers (2)

phyrrus9
phyrrus9

Reputation: 1467

if (CourseTitle == "x" && "X")
{
    not_finished=false;
}

to

if (strcmp(CourseTitle.c_str(), "x") == 0 || strcmp(CourseTitle.c_str(), "X") == 0)
{
    not_finished=false;
}

== is a pointer comparison, almost never true... "x" == "x" will even be false unless you're good with compiler flags

Make sure to

#include <string.h> //<----.h is needed!

Upvotes: 1

Thomas Matthews
Thomas Matthews

Reputation: 57688

Your problem is your comparison in the if statement:

if (CourseTitle == "x" && "X")

The proper syntax is: (variable operator variable) && (variable operator variable)

The syntax corrected:

if ((CourseTitle == "x") && (CourseTitle == "X"))  

There is a logic issue because a variable can't equal two values at the same time.

Maybe you want:

if ((CourseTitle == "x") || (CourseTitle == "X"))

which means one OR the expressions is true.

You could eliminate the two compares by transforming the string into all uppercase or all lowercase. Search the web for "C++ string transform tolower toupper".

Upvotes: 1

Related Questions