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;
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.
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.
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.