sscanf()
expects you to pass it a pointer to the variable where it can write to. But you are not passing a pointer to the variable, you are passing the value of the variable instead. That is what the compiler is complaining about. You need to use the &
address operator to create such a pointer.
Also, in sscanf()
, the %u
specifier expects a pointer to an unsigned int
, not to an int
.
Try this:
struct mystruct {
unsigned int value;
};
void SetStruct(mystruct &ms){
std::string s = "12345";
sscanf(s.c_str(), "%u", &(ms.value));
}
If you want value
to be an int
then you need to use %d
instead:
struct mystruct {
int value;
};
void SetStruct(mystruct &ms){
std::string s = "12345";
sscanf(s.c_str(), "%d", &(ms.value));
}
For these reasons, it is better to instead use C++-style type-safe parsing via the operator>>
of std::istream
, or a function like std::stoi()
or std::stoul()
, rather than use C-style parsing via sscanf()
.