0

I get a string [192:4545:454:e33]:8888, which I want are [192:4545:454:e33] and 8888, here are my codes:

#include <cstring>
#include <iostream>

int main(int argc, char const* argv[])
{
    char ip[64] = { 0 };
    int port{ 0 };

    sscanf("[192:4545:454:e33]:8888", "%[^:]:%d", ip, &port);

    std::cout << "ip: " << ip << std::endl;
    std::cout << "port: " << port << std::endl;

    return 0;
}

The output:

ip: [192:4545:454:e33
port: 0

Seems sscanf think the first ] is the match of [, so how to escape it?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
shdxiang
  • 56
  • 6

1 Answers1

0

Sorry, but maybe the following is too simple?

#include <iostream>
#include <string>

int main() {
    std::string ip{ "[192:4545:454:e33]:8888" };

    size_t pos = ip.rfind(':');

    std::cout << "\nIP:   " << ip.substr(0, pos) << "\nPort: " << ip.substr(++pos) << '\n';

    return 0; 
}

If so, then I will delete the answer.

A M
  • 14,694
  • 5
  • 19
  • 44