In C++, if I read an integer from a string, it seems it does not really matter whether I use u
or d
as conversion specifier as both accept even negative integers.
#include <cstdio>
using namespace std;
int main() {
int u, d;
sscanf("-2", "%u", &u);
sscanf("-2", "%d", &d);
puts(u == d ? "u == d" : "u != d");
printf("u: %u %d\n", u, u);
printf("d: %u %d\n", d, d);
return 0;
}
I dug deeper to find if there is any difference. I found that
int u, d;
sscanf("-2", "%u", &u);
sscanf("-2", "%d", &d);
is equivalent to
int u, d;
u = strtoul("-2", NULL, 10);
d = strtol("-2", NULL, 10);
according to cppreference.com.
Is there any difference at all between u
and d
when using these conversion specifiers for parsing, i.e. in format passed to scanf
-type functions? What is it?
The answer is the same for C and C++, right? If not, I am interested in both.
%d
: Scan an integer as a decimal signed int
. A similar conversion specifier, %i
, interprets the number as hexadecimal when preceded by 0x
and as octal when preceded by 0
. Otherwise, it is identical.
%u
: Scan an integer as a decimal unsigned int
.