Comparing C-strings

Mar 25, 2017 at 4:09pm
Hi. I made this program so i could verify if a certain molecule is an Hydroxide (if it ends in "OH") or not (it´s not for fun, it's for school). I believe the code should be correct, but for some reason it gives me wrong when it should be right, and right when it should be wrong. What is the problem here?

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
28
29
30
31
#include <iostream>
#include <cstring>

using namespace std;

bool isHydroxide(char compound[])
{
	char term[] = "OH";
	int size_str = strlen(compound);
	char str2[] = {compound[size_str - 2], compound[size_str - 1],'\0' };

	if (strcmp(str2, term))
		return true;
	else 
		return false;
}

int main()
{
	char str[10];
	cout << "Insert a molecule: ";
	cin >> str;

	if (isHydroxide(str))
		cout << "It's an Hydroxide!" << endl;
	else
		cout << "It's not an Hydroxide! :( " << endl;

	return 0;
}


When comparing the two c-strings it should give me 0 if they are equal but i debbuged the code and it gave me a value greater than 0. Why? Any Help would be great!
Thank You :)
Mar 25, 2017 at 4:23pm
When using an integer where a boolean value is expected 0 will be treated as false and everything else as true.

Line 12 is equivalent to if (strcmp(str2, term) != 0).

To get what you want you should write if (strcmp(str2, term) == 0).
Last edited on Mar 25, 2017 at 4:26pm
Mar 25, 2017 at 4:38pm
Thank You God Peter87! :) *clicks in like button*
Topic archived. No new replies allowed.