gpt4 book ai didi

C++ 从字符串中获取小时和分钟

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:57 24 4
gpt4 key购买 nike

我正在为学校编写 C++ 代码,其中我只能使用 std 库,所以没有提升。我需要解析像“14:30”这样的字符串并将其解析为:

unsigned char hour;
unsigned char min;

我们将字符串作为 C++ 字符串获取,因此没有直接指针。我尝试了这段代码的所有变体:

sscanf(hour.c_str(), "%hhd[:]%hhd", &hours, &mins);

但我总是得到错误的数据。我做错了什么。

最佳答案

正如其他人所提到的,您必须使用指定的%d 格式(或%u)。至于替代方法,我不太喜欢“因为 C++ 具有 XX 特性,所以必须使用它”,并且经常求助于 C 级函数。尽管我从不使用类似 scanf() 的东西,因为它有自己的问题。话虽这么说,这里是我将如何使用带有错误检查的 strtol() 解析您的字符串:

#include <cstdio>
#include <cstdlib>

int main()
{
unsigned char hour;
unsigned char min;

const char data[] = "12:30";
char *ep;

hour = (unsigned char)strtol(data, &ep, 10);
if (!ep || *ep != ':') {
fprintf(stderr, "cannot parse hour: '%s' - wrong format\n", data);
return EXIT_FAILURE;
}

min = (unsigned char)strtol(ep+1, &ep, 10);
if (!ep || *ep != '\0') {
fprintf(stderr, "cannot parse minutes: '%s' - wrong format\n", data);
return EXIT_FAILURE;
}

printf("Hours: %u, Minutes: %u\n", hour, min);
}

希望对您有所帮助。

关于C++ 从字符串中获取小时和分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13457250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com