Seems to skip if-statement

This code extracts the domain from an email address. The if-statement resolves to true; however, the variable at_index is not incremented. In fact, the program jumps right to the output commands. Using Visual Studio.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int main(void) {
	std::string email = "travisbickle@yahoo.com";
	std::string domain = "";

	auto at_index = email.find('@');
	auto dot_index = email.rfind('.');

	if (at_index > -1 && dot_index > at_index) {
		++at_index;
		if (at_index < email.length() && at_index < dot_index) {
			int length = dot_index - at_index;
			domain = email.substr(at_index, length);
		}
	}
        std::cout << email << std::endl;
	std::cout << "domain is: " << domain << std::endl;
Last edited on
I think the problem is that you are mixing signed and unsigned integers.

at_index is unsigned.
-1 is signed.

Before these two values can be compared they have to be converted to the same type. The compiler will therefore convert -1 to the unsigned type of at_index which results in the largest possible value of that type. No value can be larger than the largest possible value so the comparison will always result in false.
You presumably meant to compare to npos. And you should probably check dot_index, too.

 
	if (at_index != email.npos && dot_index != email.npos && dot_index > at_index) {

Last edited on
Lines 5 & 6: changed auto type to int and it works fine. Lesson learned: be wary of using auto with fundamental data types.
Last edited on
The actual lesson is to maximize your compiler warnings and don't ignore them. You should see one about comparing signed and unsigned, in both versions of your code. I showed you the proper fix. Do what you will, but you are relying on "undefined behavior" when setting an int to npos. Do you have a problem with npos?

BTW, C++ programmers don't say (void) for an empty parameter list. And there's no reason to initialize a string to "" since that's what it will be set to by its constructor.
Last edited on
Roger that, VS doesn't show the warning until I compiled it at warning level 3.

1
2
Main.cpp(13): warning C4018: '<': signed/unsigned mismatch
C:\Program Files (x86)\Microsoft Visual Studio\2019\...


I'll compile with max warnings in the future. I had to research npos (I'm brand-new to C++) and using it with the auto type. It works! Roger on the not string initializing and void w/empty parameter list.
Topic archived. No new replies allowed.