How to check if string does not equal something

Hi Guys,

Just trying to make a program and have encountered a problem.

I'm making an if statement and basically I want:

if (string does not equal "BLAH") {
BLAH BLAH
}

I don't know how to do does not equal for a string.. I tried !== but to no avail.

Thanks for the help
!=

you can use != on any of the basic types and on std::strings in the same way.
Last edited on
Thanks for the reply...

I tried that but then if I enter a valid string it still doesn't work.

For example :

if (var1 != BLAH) {
cerr << "You have entered an invalid input" << endl;
}

Even if I put BLAH in, it produces the error message??
Sorry.. It is slightly different to the reply above..

It works if theres one variable but im trying to check multiple so:

if (var1 != BLAH || var2!=BLAH2) {
cerr << "You have entered an invalid input" << endl;
}

And it's not working...? How so?
BLAH should be a string, of course.

Also are you working with actual std::strings, or char arrays? Because != doesn't work with char arrays.

Show us code. It's hard for us to see what you're doing wrong when we can't see what you're doing.
@ OP: This is an odd circumstance, could you post the relavent section of code for us? As in the entire function and any global's it may be using?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

using namespace std;

int main ()
{

	string myString ("stringcom");

	if (myString != "stringcom") {

		cout<<"Yay!"<<endl;

	}

	else 
		cout<<"..."<<endl;


cin.get(); cin.get();
}
closed account (zb0S216C)
I believe the compare( ) member of string can assist you[1].

References:
[1]http://www.cplusplus.com/reference/string/string/compare/

Wazzak
Last edited on
This is just a nitpicky thing, but most of us prefer to read the code like this. In order to use this formatting, you must either type in [code] at the beginning of the code and [/code] at the end of it, or you may press the button to the right of the text box that has the <> in it, and that will automaticly add the code formatting. Thanks! :)
Topic archived. No new replies allowed.