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

标签 c++ scanf

我正在为学校编写 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/

相关文章:

C++,其他变量受到 scanf 语句的影响

c++ - 对于 scanf(),为什么否定的扫描集 "%[^\n]"显示 "\n"的正确输出,而不是 "%[aeiou]"的扫描集 "aegis"?

c++ - const 是否适用于传递给函数的所有参数?

c++ - 使用openssl解析加密文件

c++ - C++ 中的基本 if 语句 3 值

c++ - 无法将参数 1 从 'ATL::CStringT<wchar_t,ATL::StrTraitATL<wchar_t,ATL::ChTraitsCRT<wchar_t>>>' 转换为 'const char *'

c++ - 使用 list 的 DLL 重定向

C - fscanf 未从文本文件中正确读取数字

c - fscanf 没有正确匹配

c - while循环中跳过scanf,导致死循环