c++charcstdiocstdint

Why sscanf can't read an uint64_t and a char from one string?


#include <cstdio>
#include <cstdint>
#include <cassert>

int main() {
    std::uint64_t ui;
    char c;
    auto ret = std::sscanf("111K", "%lu64%[B, K, M, G]", &ui, &c);

    assert(ret == 2);
    assert(ui == 111);
}

I tried to use sscanf to read a uint64_t and a char from one string, but it only read it ui (assertion ret == 2 fails) every time I tried this.


Solution

  • You have two issues here. First

    %lu64
    

    should be

    "%" SCNu64 
    

    to read in a 64 bit integer.

    The second issue is

    %[B, K, M, G]
    

    requires a char* or wchar_t* as its output parameter as it populates a c-string. You need to change

    char c;
    

    to at least

    char c[2] // 2 because it adds a null terminator
    

    in order capture K. We put that all together and we get

    auto ret = std::sscanf("111K", "%" SCNu64 "%[B, K, M, G]", &ui, c);
    

    Do note that

    %[B, K, M, G]
    

    is actually trying to match all of the spaces and comma inside the brackets. You could also write it as

    %[BKMG]
    

    and get the same results.