0

I have a function that takes a reference to a struct and uses sscanf to set value. However, it is complaining that

format %u expects type int* but argument has type int

void SetStruct(struct &mystruct){
   std::string s = "test";
   sscanf(s.c_str(), "%u", mystruct.value);
}

I've tried using all the & and * operators I can think of..

I am also open to not using sscanf if C++ has a better way.

errno_44
  • 151
  • 6
  • The address-of operator `&` is the correct one to use in this case, but in the right place. As in `&mystruct.value`. Of course, that requires you to pass the structure by reference, and if you don't know how to do that then please get [a good book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), or go through your class-notes more thoroughly. And consider C++ functions like [std::stoi](https://en.cppreference.com/w/cpp/string/basic_string/stol). – Some programmer dude Oct 11 '19 at 14:58
  • Also, considering the faulty input in the partial [mcve] you show, never forget to check for errors! – Some programmer dude Oct 11 '19 at 14:59

1 Answers1

0

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().

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770