I want to parse a string of the form 127.0.0.1 Down56 to ip and port. Do the following

#define DEFAULT_INTERFACE "0.0.0.0" #define DEFAULT_PORT 27000 const char* iface = DEFAULT_INTERFACE; int port = DEFAULT_PORT; size_t colonPos = str.find(":"); port = atoi(str.substr(colonPos + 1, str.size() - colonPos).c_str()); std::cout << "test1: " << argumentValue.substr(0, colonPos).c_str() << std::endl; iface = argumentValue.substr(0, colonPos).c_str(); std::cout << "test2: iface " << iface << " port " << port << std::endl; 

The conclusion is the following

test1: 127.0.0.1

test2: iface port 556

Why iface is an empty string? This is for Windows. Under Linux, it works fine, but if you first get iface, then port, then both values ​​are 556

  • @KoVadim, has already written to you why the interface is not visible. I would like to add that in any case I probably should check that the ":" is in the string. If you leave the iface char * type, then you probably need to do so if (colonPos! = String :: npos) {port = atoi (str.c_str () + colonPos + 1); // atoi () will insert itself in nil at the end c_str () iface = strndup (argumentValue.c_str (), colonPos); // here colonPos will be exactly equal to the length of the substring iface} I don’t really understand why you work with str , then with argumentValue , but apparently it’s necessary. but all the extra letters (substr, etc. here to anything). - avp
  • Run in debug and see what and how you get assigned - PaulD

1 answer 1

It is still good that it is empty. In line

 iface = argumentValue.substr(0, colonPos).c_str(); 

a temporary object is created (by the function substr), from which c_str is called. The pointer obtained in this way lives to the end of the line. In the next line there will be garbage.

It is better to write somewhere like this:

 std::string iface = DEFAULT_INTERFACE; int port = DEFAULT_PORT; size_t colonPos = str.find(":"); port = atoi(str.substr(colonPos + 1, str.size() - colonPos).c_str()); std::cout << "test1: " << argumentValue.substr(0, colonPos) << std::endl; iface = argumentValue.substr(0, colonPos); std::cout << "test2: iface " << iface << " port " << port << std::endl; 

Recommendation: Do not use c_str() and char* unnecessarily.