string compare

Hi,

I'm just trying to get string compare to work.

It assigns b = 0; So it doesn't enter the if statement.

But tt = "AGGR" so I don't see why the equality doesn't work.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include<conio.h> //For kbhit in HaltProgram
#include <stdio.h>
#include <string>
#include <fstream>
#include <cmath>
#include <time.h>
#include <iomanip> //used for setprecision 
#include <windows.h> // to get directory of application
#include <winbase.h> // to get directory of application
#include <vector>
#include <random>

using namespace std;

int main(void)
{
	string tt;
	tt = "AGGR";
	int b = tt.compare("AGGR");
	if (tt.compare("AGGR"))
		cout << tt;
	else
		cout << "not AGGR" << tt;


}
compare return 0 if the strings are equal, but in if statement 0 means false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

using namespace std;

constexpr int EQUAL = 0;

int main(void)
{
	string tt("AGGR");
	if (tt.compare("AGGR") == EQUAL)
		cout << tt;
	else
		cout << "not AGGR" << tt;
}
OK duh...

Thanks!
@jjardin61,

cppreference's std::string::compare page has an example you might want to take a look at:

https://en.cppreference.com/w/cpp/string/basic_string/compare
Just for info. .compare() is similar to the c function strcmp() where the result is either < 0 (less than), - (equal), > 0 (greater).

See http://www.cplusplus.com/reference/string/string/compare/
http://www.cplusplus.com/reference/cstring/strcmp/
To compare two std::string objects for equality, use ==.

For a three way comparison, use <=> (C++20)
https://en.cppreference.com/w/cpp/language/operator_comparison#Three-way_comparison
Last edited on
Topic archived. No new replies allowed.