Jump to content
  • Advertisement
Sign in to follow this  
Ksingh30

String comparison

This topic is 4743 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok the first time through the loop it executes the code in the proper if statement. but 2nd time throught the loop it always just goes to the else and prints out "Invalid Statement"
std::string temp;
for(;;)
{
      cin>>temp;
      if(temp=="CAR")
      {    temp.clear();
         //do stuff
      else if(temp=="CDR")
      {    temp.clear();
           //do stuff
      }

      else if(temp=="EXIT")
      {      temp.clear();
             //do stuff
      }
      else
          cout<<"Invalid Input";
}

Share this post


Link to post
Share on other sites
Advertisement
That shouldn't even compile, you are missing a closing barce after the first if statement.

Otherwise, it worked when I tested it. Care to show a bit more code?


jfl.

Share this post


Link to post
Share on other sites
oh I just wrote that real quick, lemme copy the code. for example if you want to enter "CAR" you have to type in "CAR(" its using the ( to determine its the end of the string. but it works fine, first time around the loop, then it just goes to "input error"


char temp=0;
string _T;
for(;;)
{
cout<<endl<<"input: ";
while(temp!='(')
{
temp=getchar();
if(temp=='(')
break;
else
_T.push_back(temp);
}temp=0;
if(_T=="CAR")
cout<<endl<<"CAR WORKS";
else if(_T=="CDR")
cout<<endl<<"CDR WORKS";
else if(_T=="QUOTE")
cout<<endl<<"QUOTE WORKS";
else
cout<<"INPUT ERROR";
_T.clear();
}

Share this post


Link to post
Share on other sites
I don't fully understand why you would want the user to type in CAR( and then try and look for the ( to determine the end of the string, because the string type in c++ lets you compare two strings using the == operator.


string _T;

cout << "Type in CAR: " << endl;
cin >> _T;

if(_T == CAR)
cout << "it works" << endl;
else
cout << "it doesn't" << endl;



Share this post


Link to post
Share on other sites
before you loop back to the start of the loop try putting in cin.ignore(1)

It looks like you may be leaving a character on the input so that the next time around the loop it will pickup that character and the string won't be correct.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!