Sscanf (s, "% u", & v) corresponding to signed integers

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
+4
2

.

  • %u unsigned int*; int*, UB.
  • %u -4? . : strtoul 10, , , .
+4

, . undefined: sscanf .

+3

Source: https://habr.com/ru/post/1685588/


All Articles