【问题标题】:How to escape right bracket in sscanf?如何在sscanf中转义右括号?
【发布时间】:2021-08-26 08:47:16
【问题描述】:

我得到一个字符串[192:4545:454:e33]:8888,我想要的是[192:4545:454:e33]8888,这是我的代码:

#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;
}

输出:

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

好像sscanf 认为第一个][ 的匹配项,那么如何逃脱呢?

【问题讨论】:

  • sscanf("[172.30.59.98]:8888", "%[^:]:%d", ip, &amp;port);
  • sscanf 不支持正则表达式。
  • @user3121023 适用于 IPv4,但我也有 IPv6,请检查更新的问题,谢谢
  • 此页面上的任何sscanf() 示例中都没有显示正则表达式。它确实支持带有否定的字符类。
  • 然后您可以使用strcat()ip 的末尾附加一个新括号,或者使用更多的C++ 方法等。将最后一个装饰重新添加到字符串可能是最简单的要走的路。

标签: c++


【解决方案1】:

抱歉,可能下面的内容太简单了?

#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; 
}

如果是这样,那么我将删除答案。

【讨论】:

  • ip.substr(++pos)更改为ip.substr(pos+1),以避免出现序列点问题,解决方案很好。
猜你喜欢
  • 2011-08-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2018-06-12
  • 2015-11-09
  • 2016-09-08
  • 2011-04-10
相关资源
最近更新 更多