After Cppcheck complained about the "%u"wrong format specifier for scanning into a variable int, I changed the format to "%d", but when I looked at it a second time before making the change, I thought that the intention might be to prevent negative source data. I wrote two small programs to see the difference:
% D qualifier
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const char* s = "-4";
int value = -1;
int res = sscanf(s, "%d", &value);
cout << "value:" << value << endl;
cout << "res:" << res << endl;
return 0;
}
see also https://ideone.com/OR3IKN
% U specifier
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const char* s = "-4";
int value = -1;
int res = sscanf(s, "%u", &value);
cout << "value:" << value << endl;
cout << "res:" << res << endl;
return 0;
}
see also https://ideone.com/WPWdqi
Results)
Surprisingly, in both qualifiers, the transforms take the sign:
value:-4
res:1
cppreference.com. C (scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s - cppreference.com), ++ (std:: scanf, std:: fscanf, std:: sscanf - cppreference.com) "%u" - ( ):
unsigned.
, , strtoul() 10 .
? ?
[] Undefined , , ?
, UB, , , , unsigned https://ideone.com/nNBkqN - , -1 - , "% u", , :
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const char* s = "-4";
unsigned value = -1;
cout << "value before:" << value << endl;
int res = sscanf(s, "%u", &value);
cout << "value after:" << value << endl;
cout << "res:" << res << endl;
return 0;
}
:
value before:4294967295
value after:4294967292
res:1