String comparison

Started by
5 comments, last by Ksingh30 18 years, 6 months ago
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";
}
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.
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();	}
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;


How about them apples?
well this is a pretty big project. I need the ( for later.
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.
sweet that worked like a charm. Thanks man. you are now my super hero. :)

This topic is closed to new replies.

Advertisement