sách gpt4 ai đã đi

C++字符串匹配(主机名和端口)

In lại 作者:塔克拉玛干 更新时间:2023-11-03 01:39:58 26 4
mua khóa gpt4 Nike

我想将“hostName:port”形式的 const char* hostName 分隔为 const char* hostNameFinal 和数字端口。

我目前有以下代码:

const char* hostName = "localhost:643246";

long int port;
char hostNameChar[256];
sscanf(hostName, "%s:%d", hostNameChar, &port);

hostNameChar 的输出是:localhost:643246端口的输出是一个疯狂的数字,但不是 643246

有时端口的值太大,我应该使用哪种数据类型?我如何才能正确匹配主机名,从而获得包含所需信息的 2 个变量?

1 Câu trả lời

由于您的问题标题中包含 C++,我建议您不要使用 char 数组并使用 std::string。

#include 
#include

std::string hostName = "localhost:643246";

size_t colonPos = hostName.find(':');

if(colonPos != std::string::npos)
{
std::string hostPart = hostName.substr(0,colonPos);
std::string portPart = hostName.substr(colonPos+1);

std::stringstream parser(portPart);

int port = 0;
if( parser >> port )
{
// hostname in hostPart, port in port
// could check port >= 0 and port < 65536 here
}
khác
{
// port not convertible to an integer
}
}
khác
{
// Missing port?
}

关于C++字符串匹配(主机名和端口),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5395150/

26 4 0
Bài viết được đề xuất: Linux Kiosk 软件?
Bài viết được đề xuất: mysql - 我以 root 身份登录到 mysql,但无法向用户授予额外权限
Bài viết được đề xuất: linux - 共享内存 : location and locking strategies
Bài viết được đề xuất: php - 从 PHP 运行 shell 命令 - 使用 root 权限或 sudo
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com